How do I use IValidatableObject?

前端 未结 7 1636
我在风中等你
我在风中等你 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:50

    I implemented a general usage abstract class for validation

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace App.Abstractions
    {
        [Serializable]
        abstract public class AEntity
        {
            public int Id { get; set; }
    
            public IEnumerable Validate()
            {
                var vResults = new List();
    
                var vc = new ValidationContext(
                    instance: this,
                    serviceProvider: null,
                    items: null);
    
                var isValid = Validator.TryValidateObject(
                    instance: vc.ObjectInstance,
                    validationContext: vc,
                    validationResults: vResults,
                    validateAllProperties: true);
    
                /*
                if (true)
                {
                    yield return new ValidationResult("Custom Validation","A Property Name string (optional)");
                }
                */
    
                if (!isValid)
                {
                    foreach (var validationResult in vResults)
                    {
                        yield return validationResult;
                    }
                }
    
                yield break;
            }
    
    
        }
    }
    

提交回复
热议问题