Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Validation for ViewModel Fields on ASP MVC

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?

like image 402
paddingtonMike Avatar asked Mar 09 '26 14:03

paddingtonMike


2 Answers

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

like image 160
paddingtonMike Avatar answered Mar 11 '26 03:03

paddingtonMike


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);
}
like image 39
mattytommo Avatar answered Mar 11 '26 03:03

mattytommo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!