Home >Backend Development >C++ >How to Implement Conditional Validation in ASP.NET MVC?

How to Implement Conditional Validation in ASP.NET MVC?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-08 17:31:41326browse

How to Implement Conditional Validation in ASP.NET MVC?

Implementing conditional validation in ASP.NET MVC

Data annotations in ASP.NET MVC provide a convenient way to perform validation on model properties. However, sometimes you may need to implement conditional validation rules where the validity of a field depends on the value of another field.

Example: Conditionally required fields

Consider the following scenario: We have a "Person" model that contains an "IsSenior" property and a "Senior" property that contains a description. We want the "Senior.Description" property to be a required field only if "IsSenior" is set to true.

Data annotation method

This is not possible using only data annotations. The following code demonstrates this limitation:

<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 = "*")]
    public string Description { get; set; }
}</code>

IValidatableObject method

ASP.NET MVC 3 introduces a better solution for conditional validation using the IValidatableObject interface. Your model must implement this interface and provide a Validate method that accepts a ValidationContext parameter. This method can perform custom validation logic and return a collection of ValidationResult objects if any errors are found.

<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("必须提供描述。");
    }
}</code>

By implementing the IValidatableObject interface, we can now perform conditional validation based on the value of "IsSenior". When "IsSenior" is true, the "Senior.Description" property becomes a required field.

Improved syntax (C# 6.0 and above)

In C# 6.0 and later, the Validate method can be simplified using an expression body member:

<code class="language-csharp">public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) =>
    IsSenior && String.IsNullOrEmpty(Senior?.Description)
        ? new[] { new ValidationResult("必须提供描述。") }
        : Enumerable.Empty<ValidationResult>();</code>

Through the above methods, we can effectively implement conditional verification in ASP.NET MVC. Note the use of the null conditional operator (?.) to safely access Senior.Description and avoid null reference exceptions.

The above is the detailed content of How to Implement Conditional Validation in ASP.NET MVC?. 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