你可以添加 memberNames !
return new ValidationResult("City is required", new string[] { "City", "Street" });
编辑:
我已经测试并找到了解决方案:System.ComponentModel.IDataErrorInfo !这在 javascript 客户端上不起作用,但是在提交结果时我们尝试了 :) 所以请继续使用 ValidationResult 和 memberNames 和:
public class myModel : System.ComponentModel.IDataErrorInfo
{
private Dictionary<string, List<ValidationResult>> errors;
private bool IsValidated = false;
private void Validate()
{
errors = new Dictionary<string, List<ValidationResult>>();
List<ValidationResult> lst = new List<ValidationResult>();
Validator.TryValidateObject(this, new ValidationContext(this, null, null), lst, true);
lst.ForEach(vr =>
{
foreach (var memberName in vr.MemberNames)
AddError(memberName, vr);
});
IsValidated = true;
}
private void AddError(string memberName, ValidationResult error)
{
if (!errors.ContainsKey(memberName))
errors[memberName] = new List<ValidationResult>();
errors[memberName].Add(error);
}
public string Error
{
get
{
if (!IsValidated)
Validate();
return string.Join("\n", errors
.Where(kvp => kvp.Value.Any())
.Select(kvp => kvp.Key + " : " + string.Join(", ", kvp.Value.Select(err => err.ErrorMessage)))
);
}
}
public string this[string columnName]
{
get
{
if (!IsValidated)
Validate();
if (errors.ContainsKey(columnName))
{
var value = errors[columnName];
return string.Join(", ", value.Select(err => err.ErrorMessage));
}
else
return null;
}
}
现在当前属性被标记为错误,并且 memberNames 也是!
:D
编辑 2
实际上,您可以保留简单的 DataAnnotations 来通知客户端,而在服务器端,您可以添加更复杂的业务验证:
public class myModel : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrEmpty(input.City))
yield return new ValidationResult("City is required",new string[]{"prop1","prop2"});
if (!string.IsNullOrEmpty(input.PostalCode))
if (string.IsNullOrEmpty(input.Street))
yield return new ValidationResult("Stret is required");
}
请注意,仅当 DataAnnotations 都有效时才调用Validate 方法!