Home >Backend Development >C++ >How to Implement Conditional Property Validation Using IValidatableObject in .NET?
Conditional Validation in .NET using IValidatableObject
The IValidatableObject
interface offers a powerful way to perform comprehensive object validation in .NET, including cross-property checks. However, selectively ignoring validation rules based on certain conditions can be tricky. This example demonstrates how to achieve conditional property validation effectively.
Here's a code snippet illustrating the implementation:
<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 (Enable) { // Conditionally validate Prop1 and Prop2 Validator.TryValidateProperty(Prop1, new ValidationContext(this, null, null) { MemberName = "Prop1" }, results); Validator.TryValidateProperty(Prop2, new ValidationContext(this, null, null) { MemberName = "Prop2" }, results); // Add a custom conditional validation rule if (Prop1 > Prop2) { results.Add(new ValidationResult("Prop1 must be less than or equal to Prop2")); } } return results; } }</code>
This code uses the Enable
property to control validation. If Enable
is true, it validates Prop1
and Prop2
using the [Range]
attribute and a custom rule ensuring Prop1
is not greater than Prop2
. The Validator.TryValidateProperty()
method is key; it only adds validation errors to the results
list if validation fails.
To utilize this validation:
<code class="language-csharp">public void PerformValidation() { var toValidate = new ValidateMe { Enable = true, Prop1 = 6, //This will cause a validation error Prop2 = 2 }; bool validateAllProperties = false; // Important: Set to false for conditional validation var results = new List<ValidationResult>(); bool isValid = Validator.TryValidateObject(toValidate, new ValidationContext(toValidate, null, null), results, validateAllProperties); //Process validation results (results list) }</code>
Setting validateAllProperties
to false
is crucial. This prevents Validator.TryValidateObject()
from overriding the conditional validation logic. This approach combines IValidatableObject
with conditional validation for flexible and robust object validation in your .NET applications.
The above is the detailed content of How to Implement Conditional Property Validation Using IValidatableObject in .NET?. For more information, please follow other related articles on the PHP Chinese website!