【问题标题】:TryValidateObject and IValidatableObject not triggeredTryValidateObject 和 IValidatableObject 未触发
【发布时间】:2014-02-12 12:25:57
【问题描述】:

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

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

如果 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));
//}

【问题讨论】:

  • 设计?在我看到这篇文章之前,我什至没有意识到 IValidatableObject.Validate() 方法会触发。我试图弄清楚为什么它似乎从来没有开火。你有没有找到一种方法让它每次都着火?

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2011-11-22
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2013-10-10
    • 1970-01-01
    相关资源
    最近更新 更多