首頁 >後端開發 >C++ >如何使用ivalidatableObject在ASP.NET核心中實現條件驗證?

如何使用ivalidatableObject在ASP.NET核心中實現條件驗證?

DDD
DDD原創
2025-01-28 11:46:10689瀏覽

How to Implement Conditional Validation in ASP.NET Core using IValidatableObject?

在ASP.NET Core中使用IValidatableObject實現條件驗證

IValidatableObject接口是進行ASP.NET Core對象驗證的實用工具。它允許您定義自定義驗證規則,這些規則可以比較屬性,或處理條件驗證場景。

該接口的一個常見用例是僅在特定條件下驗證某些屬性。例如,以下代碼片段演示了一個對象,其屬性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 (!this.Enable)
        {
            // 返回有效结果
            yield break;
        }
        else
        {
            // 检查Prop1和Prop2是否满足其范围要求,并相应地返回结果
            if (this.Prop1 < 1 || this.Prop1 > 5)
            {
                yield return new ValidationResult("Prop1必须在1到5之间", new[] { "Prop1" });
            }
            if (this.Prop2 < 1 || this.Prop2 > 5)
            {
                yield return new ValidationResult("Prop2必须在1到5之间", new[] { "Prop2" });
            }
        }
    }
}</code>

這種方法並非在所有情況下都最合適,因為它需要在Validate()方法中檢查Enable標誌並手動返回有效結果。

另一種方法是在Validate()方法中使用Validator.TryValidateProperty()方法。此方法允許您為特定屬性指定驗證上下文:

<code class="language-csharp">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", new[] { "Prop1", "Prop2" }));
        }
    }
    return results;
}</code>

在這種情況下,只有在驗證失敗時,Validator.TryValidateProperty()方法才會將驗證結果添加到results集合中。通過使用此方法,您可以根據對象的狀體有條件地驗證屬性,使您的驗證邏輯更靈活、更易於維護。 注意,這裡對ValidationResult添加了MemberNames,以便更清晰地指出錯誤的屬性。

以上是如何使用ivalidatableObject在ASP.NET核心中實現條件驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn