Search code examples
validationasp.net-mvc-5model-validation

Ignore required field if field is hidden in ASP.NET MVC 5


I am using ASP.NET MVC 5 where I have a model. An attribute in my model is required. However in the form on the frontend the element is not visible at first. I want the validation to take place only if the field is visible. Currently the validation takes place even if the field is not visible. My field looks like this in the frontend:

<div style="display:none;">
    @Html.TextBoxFor(Model => Model.name, "", new { @class = "adrInput form-control" })
    @Html.ValidationMessageFor(Model => Model.name, "", new { @class = "valErrorMsg" })
</div>

In the model, my field looks like this:

[Required(ErrorMessage = "Please insert name.")]
public string name{ get; set; }

How can I make sure that the validation only takes place when the element is visible? Currently the validation is always performed. No matter if the field is visible or not.


Solution

  • I solved the problem. You have to check in the controller if the element is visible. I was able to check this very easily in my application because the text box is displayed when a certain checkbox is unchecked in my form. I could then read the value of this checkbox from the model. In this way you can remove the validation:

    this.ModelState.Remove("name");