c# - 仅当另一个字段是 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; }
解决方案
看来您需要创建一个模型验证属性;
假设您的模型类是:
[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,请查看文档以获得更好的适应。
推荐阅读
- javascript - 两个特定点 P5.js 之间的嘈杂线
- java - Apache Camel RabbitMQ 消费者在不可恢复错误时自动恢复
- powershell - PowerShell - 如何检查“不包含”子句?
- postgresql - sequelize nested include table 有一个条目,但是不能从这部分查询中引用
- python - 如何使用 Cython 将带有原始数据的 std::stringstream 从 C++ 传递到 Python
- python - 这个 Python 程序有什么问题
- firebase - 每次为相同的 URI 和信息创建一个新的 Firebase 动态链接
- javascript - 内容安全策略间歇性错误
- python - 在python中计算多类分类模型的真阳性和假阳性
- python - 如何在不同的 pandas 数据框中搜索关键字并在父 DF 中更新或创建具有匹配关键字的新列