我正在尝试使用Entlib 4的验证块,但我遇到了一个问题,清楚地识别了验证结果中的无效属性。
在下面的示例中,如果City属性验证失败,我无法知道它是HomeAddress对象的City属性还是WorkAddress对象。
有没有一种简单的方法可以在不创建自定义验证器等的情况下执行此操作?
对我缺少或不理解的任何见解都将不胜感激。
谢谢。
public class Profile
{
...
[ObjectValidator(Tag = "HomeAddress")]
public Address HomeAddress { get; set; }
[ObjectValidator(Tag = "WorkAddress")]
public Address WorkAddress { get; set; }
}
...
public class Address
{
...
[StringLengthValidator(1, 10)]
public string City { get; set; }
}
答案 0 :(得分:0)
基本上我创建了一个自定义验证器,它扩展了ObjectValidator并添加了一个_PropertyName字段,该字段被添加到验证结果的键之前。
所以现在上面描述的例子中的用法是:
public class Profile
{
...
[SuiteObjectValidator("HomeAddress")]
public Address HomeAddress { get; set; }
[SuiteObjectValidator("WorkAddress")]
public Address WorkAddress { get; set; }
}
验证员类:
public class SuiteObjectValidator : ObjectValidator
{
private readonly string _PropertyName;
public SuiteObjectValidator(string propertyName, Type targetType)
: base(targetType)
{
_PropertyName = propertyName;
}
protected override void DoValidate(object objectToValidate, object currentTarget, string key,
ValidationResults validationResults)
{
var results = new ValidationResults();
base.DoValidate(objectToValidate, currentTarget, key, results);
foreach (ValidationResult validationResult in results)
{
LogValidationResult(validationResults, validationResult.Message, validationResult.Target,
_PropertyName + "." + validationResult.Key);
}
}
}
必要的属性类:
public class SuiteObjectValidatorAttribute : ValidatorAttribute
{
public SuiteObjectValidatorAttribute()
{
}
public SuiteObjectValidatorAttribute(string propertyName)
{
PropertyName = propertyName;
}
public string PropertyName { get; set; }
protected override Validator DoCreateValidator(Type targetType)
{
var validator = new SuiteObjectValidator(PropertyName, targetType);
return validator;
}
}