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

老子叫甜甜 提交于 2019-12-17 17:58:05

问题


To keep my model validation clean I would like to implement my own validation attributes, like PhoneNumberAttribute and EmailAttribute. Some of these can favorably be be implemented as simple classes that inherit from RegularExpressionAttribute.

However, I noticed that doing this breaks client side validation of these attributes. I am assuming that there is some kind of type binding that fails somewhere.

Any ideas what I can do to get client side validation working?

Code example:

public sealed class MailAddressAttribute : RegularExpressionAttribute
{
    public MailAddressAttribute()
        : base(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$")
    {
    }
}

回答1:


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).




回答2:


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-.]+$
    {

    }
}


来源:https://stackoverflow.com/questions/3627843/asp-net-mvc-data-annotations-client-side-validation-with-inherited-regularexpres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!