基于另一个属性的范围验证 [英] Range validation based on another property

查看:55
本文介绍了基于另一个属性的范围验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有FooModel模型

Currently I have the model 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; }
}

根据建议,我创建了一个自定义范围验证器

Following suggestions I created a custom range validator

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

推荐答案

您不能在range属性中,但是可以添加

You can't in the range attribute, but you could add the MVC Foolproof Validation library. Then you can set your range to be the max that your storage or primitive type will hold, then use foolproof's lessthan to constrain it to the BarMax property.

这篇关于基于另一个属性的范围验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆