ホームページ >バックエンド開発 >C++ >How to Implement Conditional Validation in ASP.NET MVC Using Data Annotations and IValidatableObject?

How to Implement Conditional Validation in ASP.NET MVC Using Data Annotations and IValidatableObject?

Patricia Arquette
Patricia Arquetteオリジナル
2025-01-08 17:47:40456ブラウズ

How to Implement Conditional Validation in ASP.NET MVC Using Data Annotations and IValidatableObject?

Implementing Conditional Validation with ASP.NET MVC Data Annotations and IValidatableObject

ASP.NET MVC's conditional validation feature lets you define validation rules that depend on other model properties. This is invaluable when certain fields need validation only under specific circumstances.

Conditional Validation Example: A Practical Scenario

Let's illustrate with a Person model containing Name, IsSenior, and a nested Senior class with a Description property. We'll require Senior.Description only if IsSenior is true.

Here's the model using data annotations (a simpler, but less flexible approach):

<code class="language-csharp">public class Person
{
    [Required(ErrorMessage = "*")]
    public string Name { get; set; }

    public bool IsSenior { get; set; }

    public Senior Senior { get; set; }
}

public class Senior
{
    [Required(ErrorMessage = "*")]  // This validation is not conditionally applied yet.
    public string Description { get; set; }
}</code>

And a corresponding view snippet (illustrative):

<code class="language-html">@Html.LabelFor(m => m.Name)
@Html.EditorFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)

@Html.LabelFor(m => m.IsSenior)
@Html.EditorFor(m => m.IsSenior)
@Html.ValidationMessageFor(m => m.IsSenior)

@Html.LabelFor(m => m.Senior.Description)
@Html.EditorFor(m => m.Senior.Description)
@Html.ValidationMessageFor(m => m.Senior.Description) </code>

Advanced Conditional Validation with IValidatableObject

For more robust conditional validation, ASP.NET MVC offers the IValidatableObject interface. Implementing its Validate method allows you to define validation logic based on the model's overall state.

Here's the improved Person model using IValidatableObject:

<code class="language-csharp">public class Person : IValidatableObject
{
    public string Name { get; set; }
    public bool IsSenior { get; set; }
    public Senior Senior { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (IsSenior && string.IsNullOrEmpty(Senior?.Description))
            yield return new ValidationResult("Description is required for senior citizens.");
    }
}</code>

This approach offers greater flexibility and control over validation rules. For comprehensive details, consult the relevant Microsoft documentation (search for "IValidatableObject" and ASP.NET MVC). The example above utilizes the null-conditional operator (?.) for added safety.

以上がHow to Implement Conditional Validation in ASP.NET MVC Using Data Annotations and IValidatableObject?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。