I have following code to test a class property:
public class RegExtTest
{
[RegularExpression(@"^[A-z0-9]{6}$", ErrorMessage = "Lot must be 6 characters alphanumeric")]
public string Lot { get; set; }
}
and a generic extension method to validate a class containing one or more of these objects
public static IEnumerable<string> ValidateObject(this object objectToValidate)
{
var result = new List<string>();
var objType = objectToValidate.GetType();
var properties = objType.GetProperties();
foreach (var propertyInfo in properties)
{
var attrs = propertyInfo.GetCustomAttributes(typeof(ValidationAttribute), true);
foreach (var attribue in attrs)
{
try
{
var validationAttr = attribue as ValidationAttribute;
if (validationAttr != null)
{
validationAttr.Validate(objectToValidate,propertyInfo.Name);
}
}
catch (Exception e)
{
if (e is ValidationException)
result.Add(e.Message);
}
}
}
return result;
}
However validation fails when value is "a23456". I unit tested this using Regex class as follows:
var isMatch = Regex.IsMatch(lbp.Lot, "^[A-z0-9]{6}$");
The above test passes. What am i doing wrong here? Is there some gotcha in RegularExpressionAttribute I am not aware off