1

Entlib 4 の検証ブロックを使用しようとしていますが、検証結果で無効なプロパティを明確に特定するという問題が発生しています。

次の例では、City プロパティが検証に失敗した場合、それが HomeAddress オブジェクトの City プロパティだったのか、WorkAddress オブジェクトの City プロパティだったのかを知る方法がありません。

カスタムバリデータなどを作成せずにこれを行う簡単な方法はありますか?

私が見逃していることや理解していないことについての洞察をいただければ幸いです。

ありがとうございました。

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 を拡張するカスタム バリデータを作成し、validationresults のキーの先頭に追加される _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 に答える