Title: Conditional Validation for ViewModel Fields on ASP MVC
I have a question about ASP MVC validtion. Let's say that I have the follwing View Model
public class PersonViewModel
{
[Required]
public string Name {get; set; }
[Required]
public string Email {get; set; }
}
According to this when I submit the form MVC will validate that both fields have values. However, in my website I have the situation where the Email can be turned off in a global site setting, so the model will only render the Name Textbox on the form. Now when I submit the form it still asks me for the Email field since it is indicated as "Required", despite there is no way the user can fill that field now.
Is there a solution for this type of scenario when using ASP MVC validations?
I seem to have found the solution:
if(EmailTurnedOff)
{
this.ViewData.ModelState.Remove("Email");
}
Then when I call ModelState.IsValid it will give me the correct answer
The solution is that you'll have to take off the Required attribute on the Email field and perform the validation yourself on post, if such a setting is set. Something like this
[HttpPost]
public ActionResult Post(PersonViewModel model)
{
//replace EmailTurnedOff with your setting
if (!EmailTurnedOff && string.IsNullOrWhiteSpace(model.Email))
{
ModelState.AddModelError("Email", "Field is Required");
}
if (ModelState.IsValid)
{
//do whatever
}
return View(model);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With