1

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

4

2 回答 2

2

你用Validate错了方法。

代替

validationAttr.Validate(objectToValidate,propertyInfo.Name);

利用

validationAttr.Validate(propertyInfo.GetValue(objectToValidate, null),propertyInfo.Name);

您必须将属性的实际值Validate传递给方法,因为RegularExpressionAttribute该类只会调用参数并.ToString()根据value其模式检查它。

但是正如杰伊在回答中所说的那样,使用Validatorclass仍然是最简单的。

于 2013-07-31T15:24:32.943 回答
2

您可以使用Validator. 有关更多详细信息,请参见此处

这应该可以解决问题。

public static IEnumerable<string> ValidateObject(this object model)
{
    var context = new ValidationContext(model);
    var results = new List<ValidationResult>();
    Validator.TryValidateObject(model, context, results, true);
    return results.Select(r => r.ErrorMessage);
}

更新

我最初忘记了true调用结束时的附加 (validateAllProperties) TryValidateObject。指定验证器true来检查每个属性和每个ValidationAttribute.

我针对您的用例进行了测试,该用例Lot = "a12345"有效(不返回错误消息)与Lot = "a1234$"确实返回错误消息。

希望这可以帮助。

于 2013-07-31T15:10:08.413 回答