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

时间:2019-08-19 08:04:07

标签: c# asp.net-mvc entity-framework validation

这是课程Report。如果Comment的值小于4,我想使ReasonIdsScore成为必需。我不能使用属性验证,因为您不能使用field作为属性参数。如何在ASP.NET MVC核心应用程序中验证这些字段?

public class Report
{
    public int Score { get; set; }
    public string Comment { get; set; }
    public int[] ReasonIds { get; set; }
}

1 个答案:

答案 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";
        }
    }
相关问题