Home >Backend Development >C++ >How to Implement Conditional Validation in IValidatableObject with Property-Level Attributes and Scenario-Based Ignoring?

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

DDD
DDDOriginal
2025-01-28 11:36:09558browse

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

Implement conditional verification in ivalidatableObject: attribute -level characteristics and scene -based ignoring

Question:

I know can be used for object verification when comparing attributes. However, I hope to use attributes to verify a single attribute and ignore specific attributes in some scenarios. Is my implementation below incorrect?

Answer: IValidatableObject

The implementation provided by
<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>
can be improved to implement the required conditions. The following is an alternative method:

uses , only when the verification fails, the verification result will be added to the

collection. If the verification is successful, it will not be added, which means success.

Execution verification:
<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() Set to results to ensure that only the attributes of

attributes can be verified, so that the

method processing conditions are allowed to verify.

<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>
This Revised Answer Maintautains the Original Image and Provides A More Concise and Accurate Explanation of the Code Example, Focusing on the Key Improvements and classing the purpose of

.. The code blocks are also formatted for better readability. validateAllProperties

The above is the detailed content of How to Implement Conditional Validation in IValidatableObject with Property-Level Attributes and Scenario-Based Ignoring?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn