ASP.NET MVC data annotations client side validation with inherited RegularExpressionAttribute ASP.NET MVC data annotations client side validation with inherited RegularExpressionAttribute asp.net asp.net

ASP.NET MVC data annotations client side validation with inherited RegularExpressionAttribute


You'll need to register a client-side validation adapter for your custom attribute. In this case you can use the existing RegularExpressionAttributeAdapter in System.Web.Mvc, since it should work exactly the same as the standard regex attribute. Then register it when your application start using:

DataAnnotationsModelValidatorProvider.RegisterAdapter(    typeof(MailAddressAttribute),    typeof(RegularExpressionAttributeAdapter));

Should you write an attribute that requires custom client-side validation, you can implement your own adapter by inheriting from DataAnnotationsModelValidator (see also Phil Haack's blog).


extending of the right answer

public class EmailAttribute : RegularExpressionAttribute{    static EmailAttribute()    {        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));    }    public EmailAttribute()        : base(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$") //^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$    {    }}