首页 > 解决方案 > 仅当另一个字段是 MVC 中验证的某个值时才使用 rang 进行验证

问题描述

如果我的模型中有食物和摄入量。当食物不为 0 时,摄入量只能大于 0。对此是否有任何内置验证?就像对 RangeIf 的验​​证,就像有 RequiredIf 一样?

[Required(ErrorMessage = ConstantMessages.Please_enter + "food")]
public string food { get; set; }

[Required(ErrorMessage = ConstantMessages.Please_enter + "intake")]
public string intake { get; set; }

标签: c#asp.net-mvc

解决方案


看来您需要创建一个模型验证属性

假设您的模型类是:

[NoZeroIntakeOnFood]
public class ModelClass
{
    public string food{ get; set; }
    public string intake { get; set; }
}

这是一个示例模型级验证(而不是属性级):

public class NoZeroIntakeOnFoodAttribute : ValidationAttribute {
    public NoZeroIntakeOnFoodAttribute() 
    {
        ErrorMessage = "Intake cannot be zero, when food has value";
    }

    public override bool IsValid(object value) 
    {
        ModelClass model = value as ModelClass;
        if (model?.food != null ) 
        {
           // the intake needs to be more than zero
           if( Convert.ToInt32(model.intake) > 0)
               return true;
           else return false;
        }

        return true;
    }
}

不要忘记把它NoZeroIntakeOnFood放在你的模型课上。当然,获取上面的代码并根据您的需要进行调整。

希望这有帮助。:)

-- 在这里,我们假设您使用的是 MVC 5 .Net Framework。如果您使用的是 Asp.Net Core MVC,请查看文档以获得更好的适应。


推荐阅读