如何在 MVC 中使用复选框验证文本框?

How to validate textbox with checkbox in MVC?

我有这个ViewModel:

   public string Address { get; set; }
   [DisplayName("Do you want Reward?")]
   public bool IsReward { get; set; }

   [Range(0,int.MaxValue,ErrorMessage="Please enter integer number")]

   [DisplayName("Reward")]
   public int Reward { get; set; }

In View IsReward 默认未选中 属性,当用户选中 Isreward 和 post 视图时,如果 Reward 文本框为空则向用户显示错误消息 "Please enter Reward".

如何使用 DataAnnotation 验证它?

试试下面的代码。如果 IsReward 为真且 Reward 文本框值为零,它将显示错误消息。

    [RewardValidation]
    public class RewardModel
    {
        public string Address { get; set; }
        [DisplayName("Do you want Reward ؟")]
        public bool IsReward { get; set; }

        [Range(0, int.MaxValue, ErrorMessage = "Please enter integer number")]

        [DisplayName("Reward")]
        public int Reward { get; set; }
    }

public class RewardValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        RewardModel app = value as RewardModel;
        if (app.IsReward && app.Reward==0)
        {
            ErrorMessage = "please enter Reward";

            return false;
        }
        return true;
    }
}

并在视图中包含 @Html.ValidationSummary(true) 以显示消息