Thursday, October 10, 2013

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

server-side:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    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<modelclientvalidationrule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRegexRule(this.ErrorMessage, this.Pattern)
            {
                ValidationType = "onedigit"
            };
        }
    }
</modelclientvalidationrule>
then, you can use the attribute
1
2
3
4
5
6
...
 
[OneDigit]
[DataType(DataType.Password)]
public string Password { get; set; }
....
client-side :
1
2
3
4
$.validator.addMethod("onedigit", function (value, element, regexp) {
    var re = new RegExp(regexp); return re.test(value);
});
jQuery.validator.unobtrusive.adapters.addSingleVal("onedigit", "pattern");