custom validator MVC + validation client side

十年热恋 提交于 2019-11-29 17:14:39
  1. Implement IClientValidatable in your attribute.

    public class FirstNameValidator : ValidationAttribute, IClientValidatable

  2. Write javascript adapter and include it in your view.

  3. Write javascript validation rule itself and include it in your view.

You can search "asp.net mvc 4 custom client side validation" for more details. For example, you can look Custom data annotation validator or How to support client side custom validation

Based on the code you are writing, you might be better off using the RegularExpressionAttribute instead. You can use a pattern such as "[A-Za-z]{1,30}$" to ensure that your FirstName is between 1 and 30 characters long. Alternatively, you can also use the RequiredAttribute to mark the field as mandatory.

The benefit of using these validators is that they are already hooked up to the client side validation in JQuery.

If you must use your own validators, then implement IClientValidatable, and write a custom JQuery validation adapter.

As an aside, in our projects we roll our own Validators that used a regex pattern matcher in the IsValid() method. We then hook that up to the existing regex validator adapter in JQuery via the IClientValidatable method. We did this so that we could control the error messages being used.

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