I have a form that has an option to enter dimensions for:
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
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.
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.
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.)
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.
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(){
...
});
...
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