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