Question

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?

Was it helpful?

Solution

$.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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top