这是课程Report
。如果Comment
的值小于4,我想使ReasonIds
和Score
成为必需。我不能使用属性验证,因为您不能使用field作为属性参数。如何在ASP.NET MVC核心应用程序中验证这些字段?
public class Report
{
public int Score { get; set; }
public string Comment { get; set; }
public int[] ReasonIds { get; set; }
}
答案 0 :(得分: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";
}
}