Home >Backend Development >C++ >How to Validate the Combined Length of Multiple Properties in ASP.NET MVC using Data Annotations?

How to Validate the Combined Length of Multiple Properties in ASP.NET MVC using Data Annotations?

DDD
DDDOriginal
2025-01-16 19:26:10681browse

How to Validate the Combined Length of Multiple Properties in ASP.NET MVC using Data Annotations?

Use data annotations to verify the combined length of multiple attributes in ASP.NET MVC

In ASP.NET MVC, it is a common practice to use the StringLength annotation to validate the length of a single property. However, there are situations where you need to verify the combined length of multiple properties. This article explores an MVC-compliant approach to achieving this goal using data annotations.

Custom validation attributes

To validate the combined length of multiple properties, you can create a custom validation property. Here is an example:

<code class="language-csharp">public class CombinedMinLengthAttribute : ValidationAttribute
{
    public CombinedMinLengthAttribute(int minLength, params string[] propertyNames)
    {
        this.PropertyNames = propertyNames;
        this.MinLength = minLength;
    }

    public string[] PropertyNames { get; private set; }
    public int MinLength { get; private set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
        var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();
        var totalLength = values.Sum(x => x?.Length ?? 0) + (value?.ToString()?.Length ?? 0); //处理空值情况

        if (totalLength < MinLength)
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }

        return ValidationResult.Success;
    }
}</code>

How to use

To use this custom property, you can use it to decorate a property in your view model:

<code class="language-csharp">public class MyViewModel
{
    [CombinedMinLength(20, "Bar", "Baz", ErrorMessage = "Foo, Bar 和 Baz 属性的组合最小长度应大于 20")]
    public string Foo { get; set; }
    public string Bar { get; set; }
    public string Baz { get; set; }
}</code>

When the model is validated, the custom property's IsValid method is called and the combined length of the specified property is validated against the specified minimum length along with the value of the decorated property. The improved code adds null value handling and avoids potential NullReferenceException.

The above is the detailed content of How to Validate the Combined Length of Multiple Properties in ASP.NET MVC using Data Annotations?. 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