Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequiredIf Conditional Validation for two variables in MVC4

I have a model class that is following

 public bool Saturday{ get; set; }

 public bool Sunday{ get; set; }

 public string Holiday{ get; set; }

In which I want to use the RequiredIf condition for the Holiday field using the both Saturday and Sunday fields. Can I use like following

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

So I don't know how to use the RequiredIf condition in my model class, So please someone help me

like image 866
Md Aslam Avatar asked Feb 05 '15 05:02

Md Aslam


2 Answers

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; }
like image 123
Chico Ribeiro Avatar answered Nov 06 '22 04:11

Chico Ribeiro


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.

like image 2
Terra-jin Avatar answered Nov 06 '22 06:11

Terra-jin