基本的に、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;
}
}