Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 unobtrusive validation - conditionally disable/enable validation

I have a form that has an option to enter dimensions for:

  • Width & Height
  • Width
  • Height

And I have two container divs that I hide/show depending on which of the three options is selected:

<div class="editor-field" id="width-container">
     @Html.EditorFor(model => model.Width)
     @Html.ValidationMessageFor(model => model.Width)
</div>

<div class="editor-field" id="height-container">
     @Html.EditorFor(model => model.Height)
     @Html.ValidationMessageFor(model => model.Height)
</div>

If height is selected, then width is not displayed on the form, how can I disable the unobtrusive validation on the Width input field in a fashion that will allow me to easily re-instate it if the user changes their mind i.e. removing data-* attributes is not an option. I'm happy to create an CustomAttribute class to handle this BUT I do not want to have to hack the standard jquery files to make this work as it makes updating to new versions a headache down the track. If all else fails I'll use my usual trick of adding a value of 0 to the fields when they are not visible and then removing it when they are shown.

EDIT:

Please be mindful that when Width is not visible it is not a "hidden" field per se it's just a input tag that's not visible to the user because the parent div has a style of display:none

like image 650
Rob Avatar asked Aug 05 '12 12:08

Rob


People also ask

How do I turn off unobtrusive validation?

You can disable the unobtrusive validation from within the razor code via this Html Helper property: HtmlHelper. ClientValidationEnabled = false; That way you can have unobtrusive validation on and off for different forms according to this setting in their particular view/partial view.

What is unobtrusive validation in MVC?

An unobtrusive validation in jQuery is a set of ASP.Net MVC HTML helper extensions.By using jQuery Validation data attributes along with HTML 5 data attributes, you can perform validation to the client-side.

What is unobtrusive validation?

With the unobtrusive way: You don't have to call the validate() method. You specify requirements using data attributes (data-val, data-val-required, etc.)

How does MVC validation work?

Validation is an important aspect in ASP.NET MVC applications. It is used to check whether the user input is valid. ASP.NET MVC provides a set of validation that is easy-to-use and at the same time, it is also a powerful way to check for errors and, if necessary, display messages to the user.


1 Answers

You can set up the jQuery validator that's processing your unobtrusive validation to ignore hidden elements:

jQuery.validator.defaults.ignore = ":hidden";

// the line above is outside any $(document).ready(...) or similar
$(document).ready(function(){
    ...
});
...
like image 72
Milimetric Avatar answered Nov 02 '22 23:11

Milimetric