未触发TryValidateObject和IValidatableObject

时间:2014-02-12 12:25:58

标签: c# validation c#-4.0 data-annotations

我有一个简单的问题(或不是)。

为什么当我验证我的对象时,下面的代码每次验证一个部分。

如果DataAnnotations失败,则不会调用IValidatableObject中的Validate。 如果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));
//}

1 个答案:

答案 0 :(得分:1)

解决方案:

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://github.com/aspnet/Mvc/issues/5366