Thursday, October 10, 2013

asp.net mvc custom regular expression validation for both of server-side and client-side

server-side:
    public class OneDigitAttribute : RegularExpressionAttribute, IClientValidatable
    {
        public OneDigitAttribute()
            : base(@"^.*(?=.*\d).+$")
        {
            ErrorMessage = "Required at least one numeric digit";
        }

        // for supporting a client-side validation through jquery.validation.unobtrusive
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRegexRule(this.ErrorMessage, this.Pattern)
            {
                ValidationType = "onedigit"
            };
        }
    }
then, you can use the attribute
  ...

  [OneDigit]
  [DataType(DataType.Password)]
  public string Password { get; set; }
  ....
client-side :

$.validator.addMethod("onedigit", function (value, element, regexp) {
    var re = new RegExp(regexp); return re.test(value);
});
jQuery.validator.unobtrusive.adapters.addSingleVal("onedigit", "pattern");