How can I disable jquery validation on readonly fields?

被刻印的时光 ゝ 提交于 2019-12-10 14:53:24

问题


The product I am working for uses JQuery validation with MVC3 working behind the scenes. I have a field that I toggle as read only (based on whether or not a dropdown's value is > 0) or not.

The trick is, this field needs to be required when it is not read-only, and needs to submit without errors when it is read-only, whether or not it has data.

How should I go about doing this?


回答1:


$.validator.setDefaults({
    ignore: ':hidden, [readonly=readonly]'
});

The default for the ignore parameter is ":hidden". By resetting the default using the above code, you make sure that jquery validate still does not act on hidden form elements, but also does not act on elements that have a readonly="readonly" attribute.

Reply to comments

That sounds odd, you may have to post some code to get more help. One thing you could try to remove the validation errors is to manually validate the form when you toggle the readonly attribute, something like this perhaps:

$('#the_text_box').attr('readonly', 'readonly');
$.validator.setDefaults(':hidden');
$('form').valid();
$.validator.setDefaults(':hidden, [readonly=readonly]');

You could also do something similar during the initial page load to avoid the instant validation error messages.

$.validator.setDefaults(':hidden, [readonly=readonly]');
$('form').valid();


来源:https://stackoverflow.com/questions/10803294/how-can-i-disable-jquery-validation-on-readonly-fields

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