如何验证与其他字段相关的字段

上课了Report。我想要 makeComment和ReasonIdsrequired if 的值Score小于 4。我不能使用属性验证,因为你不能使用字段作为属性参数。我如何在 ASP.NET MVC 核心应用程序中验证这些字段?


public class Report

{

    public int Score { get; set; }

    public string Comment { get; set; }

    public int[] ReasonIds { get; set; }

}


吃鸡游戏
浏览 47回答 1
1回答

子衿沉夜

这应该会给你你正在寻找的东西。public class Report : ValidationAttribute&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public int Score { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public string Comment { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public int[] ReasonIds { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; protected override ValidationResult IsValid(&nbsp; &nbsp; &nbsp; &nbsp; object value, ValidationContext validationContext)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(Score < 4 && (string.IsNullOrEmpty(Comment) || ReasonIds.Count() < 1))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new ValidationResult(GeScoreErrorMessage());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ValidationResult.Success;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; private string GeScoreErrorMessage()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $"If Score < 4 Comment and Reasons must be provided";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP