1

我正在尝试使用 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; }
}
4

1 回答 1

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;
    }
}
于 2009-03-03T18:19:40.710 回答