c# - 如何验证与其他字段相关的字段
问题描述
这里是类Report
。如果值小于 4 ,我想制作Comment
和要求。我不能使用属性验证,因为你不能使用字段作为属性参数。如何在 ASP.NET MVC 核心应用程序中验证这些字段?ReasonIds
Score
public class Report
{
public int Score { get; set; }
public string Comment { get; set; }
public int[] ReasonIds { get; set; }
}
解决方案
这应该给你你正在寻找的东西。
public class Report : ValidationAttribute
{
public int Score { get; set; }
public string Comment { get; set; }
public int[] ReasonIds { get; set; }
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
if(Score < 4 && (string.IsNullOrEmpty(Comment) || ReasonIds.Count() < 1))
{
return new ValidationResult(GeScoreErrorMessage());
}
return ValidationResult.Success;
}
private string GeScoreErrorMessage()
{
return $"If Score < 4 Comment and Reasons must be provided";
}
}
推荐阅读
- amazon-web-services - AWS EC2 负载均衡
- java - 使用 Tesseract OCR 将 PDF 中的扫描图像转换为文本
- html - 如何根据离子应用程序构建类型在css中应用if else?
- c# - 如何在检查器中创建功能槽?
- scala - 多个 Gatling 模拟在不同时间与不同的 rampUsers 并行
- c# - 左连接扩展方法(使用 DefaultIfEmpty)不发出 SQL 左连接
- arrays - 将双精度数的 VBA 数组输出到 Excel 中的一个单元格
- react-native - 请让我知道如何在 react-native android 中不运行以下命令的情况下更新发布 apk
- javascript - 过滤列表项
- html - 如何使用 VBA 在网站上单击组合框