views:

92

answers:

1

I'm creating a DataAnnotations validation attribute for matching emails using the same pattern as jQuery (yes, it must have been done before, but I can't find it...) and I'm not sure on exactly what I'm supposed to override and whether methods on the base classes should be called or not. Currently I have this implemnetation:

public class EmailAttribute : ValidationAttribute
{
    const string emailPattern = // long regex string
    private Regex emailRegex = new Regex(emailPattern, RegexOptions.Compiled);

    public override bool IsValid(object value)
    {
        return (value is string) && 
            emailRegex.IsMatch((string)value) && 
            base.IsValid(value);

    }
}

Is there any other methods I need to override for this to work correctly? Should I call base.IsValid(value) as above, or is it redundant/flat out wrong to do so?

Any comments are welcome.

+2  A: 

You don't need to override anything else and you should not call base.IsValid.

FYI: You might consider inheriting from RegularExpressionAttribute for this so that you pick up client side options. For example...

public class EmailAttribute : RegularExpressionAttribute
{
  public EmailAttribute() :
    base(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$")
  {
    ErrorMessage = "Please enter a valid email address";
  }  
}

Also, this may be useful to you:

http://foolproof.codeplex.com/

It's a set of validators that should have been in MVC. Nicely done and the source is instructive. Hasn't moved since May, hoping it's still active.

Rob
Thanks a lot for the input! This made things much clearer. Also, thanks for the tip about inheriting RegularExpressionAttribute =)
Tomas Lycken