In the field of data verification, IvalidatableObject interface plays a vital role, which allows object -level verification and can compare different attributes of objects. When you need to verify a single attribute and at the same time, you can selectively ignore certain verification failure in specific scenarios, avalidatableObject provides a flexible solution.
This article will introduce how to use IvalidatableObject to implement conditional verification.
Method to verify the attribute. If this attribute is disabled, the effective results are returned and the status of Validate()
and Enabled
is ignored. However, if this attribute is enabled, you will check whether Prop1
and Prop2
meet the scope requirements. Prop1
Prop2
The steps of effective implementation of conditional verification are as follows:
Create verification classes:
[Required]
In the [Range]
method, use Validate()
method, check the conditions (such as Validator.TryValidateProperty()
attributes) to determine whether the verification failure of certain attributes needs to be ignored. Validate()
Enable
Performing object level verification.
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; } }
The above is the detailed content of How to Implement Conditional Validation Using IValidatableObject?. For more information, please follow other related articles on the PHP Chinese website!