我有一个简单的问题(或者不是)。
为什么当我验证我的对象时,下面的代码每次验证一个部分。
如果验证失败,则不会调用IValidatableObject中的DataAnnotations。如果DataAnnotations正常,则从IValidatableObject调用Validate。
我的问题是:为什么?我看不出有什么理由这样做。我是不是遗漏了什么?
这是我的类(例如):
class Foo : IValidatableObject
{
[Required]
public DateTime Date { get; set; }
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var errors = new List<ValidationResult>();
if (Date.Ticks > DateTime.Today.Ticks)
{
errors.Add(new ValidationResult("Some error.", new[] { "Date" }));
}
return errors;
}
}这是我的验证:
var dto = new Foo();
validationResults = new List<ValidationResult>();
var context = new ValidationContext(dto, null, null);
Validator.TryValidateObject(dto, context, validationResults, true);
// Force
//var model = dto as IValidatableObject;
//if (model != null)
//{
// validationResults.AddRange(model.Validate(context));
//}发布于 2018-09-03 21:26:25
解决方案:
private void ValidateIValidatableObject(IValidatableObject validatableObject, IList<ValidationResult> errors)
{
var validations = validatableObject.Validate(null).ToList();
validations.Where(vr => vr.MemberNames == null)
.ToList()
.ForEach(vr => errors.Add(new ValidationResult(vr.ErrorMessage)));
validations.Where(vr => vr.MemberNames != null)
.SelectMany(vr => vr.MemberNames.Select(mn => new { MemeberName = mn, vr.ErrorMessage }))
.ToList()
.ForEach(vr => errors.Add(new ValidationResult(vr.ErrorMessage, new string[] { vr.MemeberName })));
}用法:
IList<ValidationResult> errors = new List<ValidationResult>();
ValidationContext context = new ValidationContext(model, null, null);
Validator.TryValidateObject(model, context, errors, true);
if (model is IValidatableObject validatableObject)
{
ValidateIValidatableObject(validatableObject, errors);
}https://stackoverflow.com/questions/21727926
复制相似问题