21

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}$")
    {
    }
}
3
  • But it is a RegularExpressionAttribute and it has a regular expression, which works just fine if it's explicitly defined in the model. Commented Sep 2, 2010 at 14:24
  • Exactly what I was about to ask Commented Sep 28, 2010 at 8:51
  • Possible duplicate of Custom DataAnnotations Validator Derived from RegularExpressionAttribute Commented Apr 11, 2019 at 18:54

2 Answers 2

32

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

Sign up to request clarification or add additional context in comments.

1 Comment

How to register adapter from the place where I defined attribute. This implementation requires knowing attributes. I can not pass DLL to another developer and ask to use attributes I should also ask him to add some code to his asax file. Is there more less coupled way?
9

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

    }
}

1 Comment

For some reason, even though the static constructor was being called, this was not generating the client side validation markup. So I added the registration to Application_Start(), in Global.asax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.