How do I use IValidatableObject?

前端 未结 7 1759
我在风中等你
我在风中等你 2020-11-22 02:59

I understand that IValidatableObject is used to validate an object in a way that lets one compare properties against each other.

I\'d still like to have

7条回答
  •  离开以前
    2020-11-22 03:37

    Just to add a couple of points:

    Because the Validate() method signature returns IEnumerable<>, that yield return can be used to lazily generate the results - this is beneficial if some of the validation checks are IO or CPU intensive.

    public IEnumerable Validate(ValidationContext validationContext)
    {
        if (this.Enable)
        {
            // ...
            if (this.Prop1 > this.Prop2)
            {
                yield return new ValidationResult("Prop1 must be larger than Prop2");
            }
    

    Also, if you are using MVC ModelState, you can convert the validation result failures to ModelState entries as follows (this might be useful if you are doing the validation in a custom model binder):

    var resultsGroupedByMembers = validationResults
        .SelectMany(vr => vr.MemberNames
                            .Select(mn => new { MemberName = mn ?? "", 
                                                Error = vr.ErrorMessage }))
        .GroupBy(x => x.MemberName);
    
    foreach (var member in resultsGroupedByMembers)
    {
        ModelState.AddModelError(
            member.Key,
            string.Join(". ", member.Select(m => m.Error)));
    }
    

提交回复
热议问题