Client-side validation does not work when inherting from RequiredAttribute in ASP.NET MVC 3?

*爱你&永不变心* 提交于 2019-12-05 10:52:42

You can fix this by adding the following code in Global.asax: (found the answer here)

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredLocalizableAttribute), typeof(RequiredAttributeAdapter));

Alternatively, using marcind's solution, I found that the constructor for ModelClientValidationRequiredRule requires an error message. Here is an updated version that includes the display name for the field:

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        string msg = FormatErrorMessage(metadata.GetDisplayName());
        yield return new ModelClientValidationRequiredRule(msg);
    }

It's only client-side validation that does not work with inherited attributes. The reason for that is that MVC uses strict type equality when mapping server-side attributes to client validation behaviors.

To work around this you will need your custom attribute to implement IClientValidatable:

public class MyRequiredAttribute : IClientValidatable {
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
         yield return new ModelClientValidationRequiredRule();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!