MVC 3 unobtrusive validation - conditionally disable/enable validation

◇◆丶佛笑我妖孽 提交于 2019-12-29 08:43:08

问题


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


回答1:


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(){
    ...
});
...



回答2:


So it seems that this is the answer to my question (I went hunting again on Google hard to search for things that didn't relate to "hidden" fields):

https://stackoverflow.com/a/7673985/491950

e.g.

$("#height-container input[type='text']").attr("disabled", "disabled");

Thanks for your answers.



来源:https://stackoverflow.com/questions/11816471/mvc-3-unobtrusive-validation-conditionally-disable-enable-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!