MVC: Override default ValidationMessage

前端 未结 8 2138
鱼传尺愫
鱼传尺愫 2020-12-13 15:05

In the world of MVC I have this view model...

public class MyViewModel{

[Required]
public string FirstName{ get; set; }    }

...and this s

8条回答
  •  一向
    一向 (楼主)
    2020-12-13 15:56

    This worked for me. Carefully read the comments inside the code. (Based on Chad's answer).

     // Keep the name the same as the original, it helps trigger the original javascript 
     // function for client side validation.
    
            public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute, IClientValidatable
                {
                    public RequiredAttribute()
                    {
                        this.ErrorMessage = "Message" // doesnt get called again. only once.
                    }
    
                    public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
                    {
                        yield return new ModelClientValidationRule
                        {
                            ErrorMessage = "Message", // this gets called on every request, so it's contents can be dynamic.
                            ValidationType = "required"
                        };
                    }
                }
    

提交回复
热议问题