基本上
我創建的延伸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;
}
}