首先,感谢@ paper1337为我指出了正确的资源…我没有注册,所以我不能投票给他,如果有人读过,请这样做。
这是完成我尝试做的事情的方法。
可验证的类:
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; }}Validator.TryValidateProperty()如果验证失败,则使用将添加到结果集合中。如果没有失败的验证,则不会向结果集合添加任何内容,这表示成功。
进行验证:
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); }validateAllProperties为使此方法起作用,设置为false
很重要。如果
validateAllProperties为false,则仅
[Required]检查具有属性的属性。这使
IValidatableObject.Validate()方法可以处理条件验证。



