Home >Backend Development >C++ >How to Implement Conditional Validation in IValidatableObject with Property-Level Attributes and Scenario-Based Ignoring?
Question:
I know can be used for object verification when comparing attributes. However, I hope to use attributes to verify a single attribute and ignore specific attributes in some scenarios. Is my implementation below incorrect?
Answer: IValidatableObject
<code class="language-csharp">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 是否满足其范围要求 // 并相应地返回。 } } }</code>can be improved to implement the required conditions. The following is an alternative method:
uses , only when the verification fails, the verification result will be added to the
collection. If the verification is successful, it will not be added, which means success.Execution verification:
<code class="language-csharp">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; } }</code>
Validator.TryValidateProperty()
Set to results
to ensure that only the attributes of
method processing conditions are allowed to verify.
<code class="language-csharp">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); }</code>This Revised Answer Maintautains the Original Image and Provides A More Concise and Accurate Explanation of the Code Example, Focusing on the Key Improvements and classing the purpose of
.. The code blocks are also formatted for better readability. validateAllProperties
The above is the detailed content of How to Implement Conditional Validation in IValidatableObject with Property-Level Attributes and Scenario-Based Ignoring?. For more information, please follow other related articles on the PHP Chinese website!