【问题标题】:How to validate field related to another fields如何验证与其他字段相关的字段
【发布时间】:2019-08-19 08:04:07
【问题描述】:
这里是Report 类。如果Score 的值小于4,我想让Comment 和ReasonIds 成为必需。我不能使用属性验证,因为你不能使用字段作为属性参数。如何在 ASP.NET MVC 核心应用程序中验证这些字段?
public class Report
{
public int Score { get; set; }
public string Comment { get; set; }
public int[] ReasonIds { get; set; }
}
【问题讨论】:
标签:
c#
asp.net-mvc
entity-framework
validation
【解决方案1】:
这应该可以满足您的需求。
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";
}
}