Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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}$")
    {
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
781 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...