When implementing a DataAnnotations validation attribute, should I call base.IsValid()?
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 a开发者_如何学JAVAnd 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...
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.
精彩评论