RequiredIf Conditional Validation for two variables in MVC4

后端 未结 3 1467
眼角桃花
眼角桃花 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<ValidationResult> Validate(ValidationContext validationContext)
        {
            var result = new List<ValidationResult>();
    
            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.

    0 讨论(0)
  • 2021-02-08 04:56

    Maybe try this in your model:

    [Required]
    public bool Saturday{ get; set; }
    
    [Required]
    public bool Sunday{ get; set; }
    
    [NotMapped]
    public bool SatSun
    {
        get
        {
            return (!this.Saturday && !this.Sunday);
        }
    }
    
    [RequiredIf("SatSun",true)]
    public string Holiday{ get; set; }
    
    0 讨论(0)
  • 2021-02-08 04:57

    My Project has RequiredIf in it.

    [Required]
    public int SalesID { get; set; }
    
    [RequiredIf("SalesID==1", ErrorMessage = "License is required.")]
    public string License{ get; set; }
    

    It shows error message 'License is required.' when License is left blank only if SalesID is 1. License cannot be blank if SalesID is 1.

    For your code it should be something like

    [RequiredIf("Sunday,Saturday",AllowEmptyStrings=false)]
    public string Holiday{ get; set; }
    

    It means if Sunday and Saturday are true you can allow Holiday property to be an Empty String.

    0 讨论(0)
提交回复
热议问题