You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET MVC中使用数据注解验证最大年龄大于最小年龄?

Fixing "MaxAge Must Be Greater Than MinAge" Validation in ASP.NET MVC

Hey there, let's sort out that age validation issue in your model. First off, your current use of the Compare attribute is incorrect—this attribute is built to verify two properties have equal values (think password and confirm password), not to check if one is greater than the other.

Below are two straightforward solutions to implement the "MaxAge > MinAge" validation logic you need:

Solution 1: Custom Data Annotation Attribute

This approach is great if you need to reuse this validation across multiple models, as it keeps the logic encapsulated and follows standard data annotation patterns.

First, create the custom validation attribute class:

using System.ComponentModel.DataAnnotations;
using System.Reflection;

public class GreaterThanAttribute : ValidationAttribute
{
    private readonly string _comparisonPropertyName;

    public GreaterThanAttribute(string comparisonPropertyName)
    {
        _comparisonPropertyName = comparisonPropertyName;
        ErrorMessage = "Maximum Age Should be Greater than Minimum Age !";
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // Get the property we're comparing against
        var comparisonProperty = validationContext.ObjectType.GetProperty(_comparisonPropertyName);
        if (comparisonProperty == null)
        {
            return new ValidationResult($"Could not find property: {_comparisonPropertyName}");
        }

        var comparisonValue = comparisonProperty.GetValue(validationContext.ObjectInstance);

        // Skip null checks since [Required] already handles that
        if (value == null || comparisonValue == null)
        {
            return ValidationResult.Success;
        }

        // Check if MaxAge is less than or equal to MinAge
        if ((int)value <= (int)comparisonValue)
        {
            return new ValidationResult(ErrorMessage);
        }

        return ValidationResult.Success;
    }
}

Now update your model to use this custom attribute instead of Compare:

public class ModelForm { 
    [Required] 
    [Range(10, 70, ErrorMessage = "Enter the minimum age between 10 to 70 !" )] 
    public int MinAge { get; set; } 

    [Required] 
    [GreaterThan(nameof(MinAge))] // Link to the MinAge property for comparison
    public int MaxAge { get; set; } 
}

Solution 2: Implement IValidatableObject

If this validation is only needed for this specific model, implementing IValidatableObject directly in the model is a simpler, more lightweight option:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

public class ModelForm : IValidatableObject
{ 
    [Required] 
    [Range(10, 70, ErrorMessage = "Enter the minimum age between 10 to 70 !" )] 
    public int MinAge { get; set; } 

    [Required] 
    public int MaxAge { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (MaxAge <= MinAge)
        {
            yield return new ValidationResult(
                "Maximum Age Should be Greater than Minimum Age !",
                new[] { nameof(MaxAge) } // Associate the error with the MaxAge property
            );
        }
    }
}

Also, quick note: I fixed a typo in your original code—you had ErrorMesaage instead of ErrorMessage in the Range attribute. Both solutions above include the corrected spelling.

内容的提问来源于stack exchange,提问作者Adarsh Bhalani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 00:08:11