基于另一个属性的范围验证

时间:2013-09-23 09:39:55

标签: asp.net-mvc asp.net-mvc-4

目前我有模型FooModel

public class FooModel
{
    [Range(0.001, 10000, ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")]
    [RangeValidator("BarMax")]
    public decimal? Bar { get; set; }

    public decimal BarMax { get; set; }
}

以下建议我创建了自定义范围验证器

public class RangeValidator : ValidationAttribute
{
    private readonly string dependentPropery;

    public RangeValidator(string dependentpropery)
        : base()
    {
        this.dependentPropery = dependentpropery;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        System.Reflection.PropertyInfo property = validationContext.ObjectType.GetProperty(this.dependentPropery);
        if (property == null)
        {
            return new ValidationResult(string.Format("Unknown Property {0}", this.dependentPropery));
        }

        var value1 = property.GetValue(validationContext.ObjectInstance, null) as decimal?;
        if (!value1.HasValue)
        {
            return null;
        }

        decimal actualValue;

        if (value == null)
        {
            return new ValidationResult("Value can not be empty.");
        }

        decimal.TryParse(value.ToString(), out actualValue);
        if (actualValue <= 0)
        {
            return new ValidationResult(string.Format("{0} Value can not be empty.", this.dependentPropery));
        }

        return actualValue > value1.Value ? new ValidationResult(string.Format("Value cannot exceed {0} {1}.", this.dependentPropery, value1.Value)) : null;
    }
} 

1 个答案:

答案 0 :(得分:1)

您不能在范围属性中,但可以添加MVC Foolproof Validation库。 然后,您可以将范围设置为存储或基元类型将保留的最大范围,然后使用万无一失的小于将其限制为BarMax属性。