We were using Evil Validation library for a while, works OK, but doesn’t support WPF/Silverlight and MVC very well. Fortunately, it’s not too hard to convert it to DataAnnotations.
Evil code example:
class EmailAddress
{
public EmailAddress(string value)
{
Value = value;
}
[ValidateRegex(@"\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}", "Invalid recipient email address")]
public string Value { get; set; }
}
public static bool ValidateEmailAddress(string emailAddress)
{
return ((new EmailAddress(emailAddress)).IsValid());
}
To DataAnnotation:
class EmailAddress
{
public EmailAddress(string value)
{
Value = value;
}
[RegularExpression(@"\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}", ErrorMessage = "Invalid recipient email address")]
public string Value { get; set; }
}
public static bool ValidateEmailAddress(string emailAddress)
{
EmailAddress emailToValidate = new EmailAddress(emailAddress);
// Watchout the last bool flag, indicate whether validate all properties. (What else? just modified one?)
return Validator.TryValidateObject(emailToValidate, new ValidationContext(emailToValidate, null, null), null, true);
// For one property model, we can also use this syntax.
ValidationContext validationContext = new ValidationContext(emailToValidate, null, null);
validationContext.MemberName = "Value";
return Validator.TryValidateProperty(emailAddress,
validationContext
, null);
}
