为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
吃鸡游戏 2023-09-09 16:17:17
上课了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; }}
查看完整描述

1 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

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


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

        }

    }


查看完整回答
反对 回复 2023-09-09
  • 1 回答
  • 0 关注
  • 44 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信