首页 > 解决方案 > 如何验证与其他字段相关的字段

问题描述

这里是类Report。如果值小于 4 ,我想制作Comment和要求。我不能使用属性验证,因为你不能使用字段作为属性参数。如何在 ASP.NET MVC 核心应用程序中验证这些字段?ReasonIdsScore

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

标签: c#asp.net-mvcentity-frameworkvalidation

解决方案


这应该给你你正在寻找的东西。

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";
        }
    }

推荐阅读