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

How to Validate Combined Length of Multiple Properties in ASP.NET MVC?

DDD
DDDOriginal
2025-01-16 19:37:11827browse

How to Validate Combined Length of Multiple Properties in ASP.NET MVC?

Using data annotations to implement ASP.NET MVC multi-attribute combination verification

In ASP.NET MVC, you can easily use the StringLength data annotation to validate the length of a single property. However, in some cases you may need to verify the combined length of multiple string properties. This article describes the recommended MVC approach to achieving this using custom data annotations.

Scheme: Custom validation attributes

To validate the combined length, create a custom validation attribute:

<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 < this.MinLength)
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }
        return ValidationResult.Success;
    }
}</code>

How to use

In your view model, decorate the desired properties with custom properties:

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

With this setting, if the combined length of the Foo, Bar, and Baz properties is less than the specified minimum length, model validation will fail with the error message defined in the properties. Null value handling has been added to the code to avoid exceptions caused by null attribute values. Error messages have also been localized to be more user-friendly.

The above is the detailed content of How to Validate Combined Length of Multiple Properties 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