Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Required Validation Specific Field in the View ASP.NET MVC 4

if someone could give me some hint I would appreciate.

I'm searching for a while, and I even found a post I thought it would solve my problem, but it didn't.

Disable Required validation attribute under certain circumstances

Basically I have a simple User.cs model where I have username, FirstName, LastName and SignupDate

All have the required annotation and I would like to solve this without erasing the Required tag.

After I generate the view, I erase in the view the html code for the SignupDate:

 <div class="editor-label">
        @Html.LabelFor(model => model.SignupDate)
 </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.SignupDate)
        @Html.ValidationMessageFor(model => model.SignupDate)
 </div>

When I click submit it does not work.

Also if I do the suggested in the other post

<div class="editor-label">
        @Html.LabelFor(model => model.SignupDate)
</div>
<div class="editor-field">
       @Html.TexBoxFor(model => model.SignupDate, new { data_val = false })
</div>

If I leave it as blank also does not work..

Any suggestions? Thanks!!

like image 724
user1837862 Avatar asked Jan 15 '23 18:01

user1837862


1 Answers

You can disable client validations on the view and remove the errors on the modelstate for those entities you don't want to validate the value.

In my case I wanted to change a Password only if the user typed one. Using Html.HiddenFor was not a good approach due to sends the password to the client every time, and password shouldn't be sent.

What I did was to disable the client validations on the view

@model MyProject.Models.ExistingModelWithRequiredFields

@{
    ViewBag.Title = "Edit";
    Html.EnableClientValidation(false);
}

That allows me to submit the form even with empty values. Please note that all client validations are ignored, however server validations still run, so you need to clear those you don't need to be executed. In order to do this, go to the action in the controller and remove the errors for each property you need to

public ActionResult Edit(ExistingModelWithRequiredFields updatedModel)
{
    var valueToClean = ModelState["RequiredPropertyName"];
    valueToClean.Errors.Clear(); 
    if(ModelState.IsValid)
    {
        ...
        //Optionally you could run validations again 
        if(TryValidateModel(updatedModel)
        {
            ...
        }
        ...
    }
    ...
}
like image 69
Jonathan Morales Vélez Avatar answered Jan 19 '23 00:01

Jonathan Morales Vélez