zoukankan      html  css  js  c++  java
  • How do I use IValidatableObject? 使用IValidatableObject添加自定义属性验证

    Here's how to accomplish what I was trying to do.

    Validatable class:

    public class ValidateMe : IValidatableObject
    {
        [Required]
        public bool Enable { get; set; }
    
        [Range(1, 5)]
        public int Prop1 { get; set; }
    
        [Range(1, 5)]
        public int Prop2 { get; set; }
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List<ValidationResult>();
            if (this.Enable)
            {
                Validator.TryValidateProperty(this.Prop1,
                    new ValidationContext(this, null, null) { MemberName = "Prop1" },
                    results);
                Validator.TryValidateProperty(this.Prop2,
                    new ValidationContext(this, null, null) { MemberName = "Prop2" },
                    results);
    
                // some other random test
                if (this.Prop1 > this.Prop2)
                {
                    results.Add(new ValidationResult("Prop1 must be larger than Prop2"));
                }
            }
            return results;
        }
    }
    

    Using Validator.TryValidateProperty() will add to the results collection if there are failed validations. If there is not a failed validation then nothing will be add to the result collection which is an indication of success.

    Doing the validation:

        public void DoValidation()
        {
            var toValidate = new ValidateMe()
            {
                Enable = true,
                Prop1 = 1,
                Prop2 = 2
            };
    
            bool validateAllProperties = false;
    
            var results = new List<ValidationResult>();
    
            bool isValid = Validator.TryValidateObject(
                toValidate,
                new ValidationContext(toValidate, null, null),
                results,
                validateAllProperties);
        }
    

    It is important to set validateAllProperties to false for this method to work. When validateAllProperties is false only properties with a [Required] attribute are checked. This allows the IValidatableObject.Validate() method handle the conditional validations.

    https://stackoverflow.com/questions/3400542/how-do-i-use-ivalidatableobject

  • 相关阅读:
    hdu 4144 状态压缩dp
    hdu 4118 树形dp
    hdu 4115 2-SAT判定
    hdu 4085 斯坦纳树
    hdu 3311 斯坦纳树
    hdu 4081 最小生成树+树形dp
    hdu 4424 并查集
    洛谷P2661信息传递
    洛谷P2746校园网
    树状数组模板
  • 原文地址:https://www.cnblogs.com/dupeng0811/p/how-do-i-use-ivalidatableobject.html
Copyright © 2011-2022 走看看