掌握條件屬性驗證
接口是用於綜合對象驗證的強大工具,對於驗證具有期間依賴性的複雜對象特別有用。 該接口允許驗證取決於同一對像中其他屬性的值。 但是,將其與單個屬性驗證屬性(例如或IValidatableObject
)相結合需要仔細考慮。
[Required]
[Range]
方法提供了執行這些條件檢查的機制。 假設您只有在
>和IValidatableObject.Validate()
。 您將如何實現此處:Prop1
Prop2
至關重要的是,當使用Enable
>時,將
<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 (!Enable) { return Enumerable.Empty<ValidationResult>(); } var validationResults = new List<ValidationResult>(); // Add conditional validation rules here. For example: if (Prop1 < 1 || Prop1 > 5) { validationResults.Add(new ValidationResult("Prop1 must be between 1 and 5", new[] { nameof(Prop1) })); } if (Prop2 < 1 || Prop2 > 5) { validationResults.Add(new ValidationResult("Prop2 must be between 1 and 5", new[] { nameof(Prop2) })); } return validationResults; } }</code>>。這可以防止框架自動驗證具有
> Validator.TryValidateObject()
的屬性的屬性,從而確保您的條件邏輯在validateAllProperties
>中優先。 這允許在單個財產驗證與有條件的,交叉特性驗證之間進行乾淨的關注點。
以上是如何使用IvalidatableObject執行條件性屬性驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!