How do I use IValidatableObject? 使用IValidatableObject添加自定义属性验证
2018-01-17 20:10
423 查看
Here's how to accomplish what I was trying to do.
Validatable class:
Using
Doing the validation:
It is important to set
https://stackoverflow.com/questions/3400542/how-do-i-use-ivalidatableobject
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
validateAllPropertiesto false for this method to work. When
validateAllPropertiesis 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
相关文章推荐
- 使用HashSet和TreeSet存储多个商品信息,遍历并输出;其中商品属性:编号,名称,单价,出版社;要求向其中添加多个相同的商品,验证集合中元素的唯一性。 提示:向HashSet中添加自定义
- How to use the windows active directory to authenticate user via logon form 如何自定义权限系统,使用 active directory验证用户登录
- 说说Android 两种为自定义组件添加属性的使用方法和区别
- 说说Android 两种为自定义组件添加属性的使用方法和区别
- Bigcommerce: 给模板添加一个自定义的产品属性,使用$GLOBALS全局变量调用
- 说说Android 两种为自定义组件添加属性的使用方法和区别
- How Do I Use the Windows System Restore Utility?——如何使用window 系统还原工具?
- 说说Android 两种为自定义组件添加属性的使用方法和区别
- 使用declare-styleable给自定义控件添加自定义属性
- category使用 objc_setAssociatedObject/objc_getAssociatedObject 实现添加属性
- category使用 objc_setAssociatedObject/objc_getAssociatedObject 实现添加属性
- IValidatableObject实现model自定义验证
- 说说Android 两种为自定义组件添加属性的使用方法和区别
- category使用 objc_setAssociatedObject/objc_getAssociatedObject 实现添加属性
- 说说Android 两种为自定义组件添加属性的使用方法和区别
- 取得ie 里面 自定义函数或者属性的集合 使用RuntimeObject()
- Android 两种为自定义组件添加属性的使用方法和区别
- 如何使用th:each属性迭代模板-原标题:How To Use th:each For Iteration In Thymeleaf Template?
- Javascript创建自定义对象 创建Object实例添加属性和方法
- category使用 objc_setAssociatedObject/objc_getAssociatedObject 实现添加属性