RequiredIf Conditional Validation for two variables in MVC4

后端 未结 3 1470
眼角桃花
眼角桃花 2021-02-08 04:29

I have a model class that is following

 public bool Saturday{ get; set; }

 public bool Sunday{ get; set; }

 public string Holiday{ get; set; }
3条回答
  •  天涯浪人
    2021-02-08 04:55

    If the need for more complex validation arises, I'd recommend implementing IValidatableObject.

    public class YourModel : IValidatableObject
    {
        public bool Saturday{ get; set; }
    
        public bool Sunday{ get; set; }
    
        public string Holiday{ get; set; }
    
        public IEnumerable Validate(ValidationContext validationContext)
        {
            var result = new List();
    
            if (Saturday == false && Sunday == false && string.IsNullOrEmpty(Holiday))
            {
                result.Add(new ValidationResult("Holiday is required outside weekends"));
            }
    
            return result;
        }
    }
    
    

    If you combine property checks with IValidatableObject, be sure to note this behaviour.

提交回复
热议问题