实现 IValidatableObject 中的条件验证:属性级特性和基于场景的忽略
问题:
我知道 IValidatableObject
可用于在比较属性时进行对象验证。但是,我希望使用属性来验证单个属性,并在某些场景中忽略特定的属性失败。我的以下实现是否不正确?
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) { if (!this.Enable) { // 在此处返回有效结果。 // 如果整个对象未“启用”,我不关心 Prop1 和 Prop2 是否超出范围 } else { // 在此处检查 Prop1 和 Prop2 是否满足其范围要求 // 并相应地返回。 } } }
答案:
提供的实现可以改进以实现所需的条件验证。以下是一种替代方法:
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); // 其他一些随机测试 if (this.Prop1 > this.Prop2) { results.Add(new ValidationResult("Prop1 必须大于 Prop2")); } } return results; } }
通过使用 Validator.TryValidateProperty()
,只有当验证失败时,验证结果才会添加到 results
集合中。如果验证成功,则不会添加任何内容,表示成功。
执行验证:
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
可确保仅验证具有 [Required]
属性的属性,从而允许 IValidatableObject.Validate()
方法处理条件验证。
This revised answer maintains the original image and provides a more concise and accurate explanation of the code example, focusing on the key improvements and clarifying the purpose of validateAllProperties
. The code blocks are also formatted for better readability.
以上是如何在具有属性级属性和基于方案的忽略的IvalidatableObject中实现条件验证?的详细内容。更多信息请关注PHP中文网其他相关文章!