首頁 >後端開發 >C++ >如何在具有屬性級屬性和基於方案的忽略的IvalidatableObject中實現條件驗證?

如何在具有屬性級屬性和基於方案的忽略的IvalidatableObject中實現條件驗證?

DDD
DDD原創
2025-01-28 11:36:09558瀏覽

How to Implement Conditional Validation in IValidatableObject with Property-Level Attributes and Scenario-Based Ignoring?

實現 IValidatableObject 中的條件驗證:屬性級特性和基於場景的忽略

問題:

我知道 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>

答案:

提供的實現可以改進以實現所需的條件驗證。以下是一種替代方法:

<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(),只有當驗證失敗時,驗證結果才會添加到 results 集合中。如果驗證成功,則不會添加任何內容,表示成功。

執行驗證:

<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>

validateAllProperties 設置為 false 可確保僅驗證具有 [Required] 屬性的屬性,從而允許 IValidatableObject.Validate() 方法處理條件驗證。

This revised answer maintains the original image and provides a more concise and accurate explanation of the code example, focusing on the key improvements and clarifying the purpose of validateAllProperties. The code blocks are also formatted for better readability.

以上是如何在具有屬性級屬性和基於方案的忽略的IvalidatableObject中實現條件驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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