6

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?

Brisbe
  • 1,588
  • 2
  • 20
  • 42

1 Answers1

16
$.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();
danludwig
  • 46,965
  • 25
  • 159
  • 237
  • Thank you, this does seem to be doing the trick for letting the client side validation not reject the page. At the same time, though, when I load the page for the first time, the validators instantly show messages that they are invalid for all the blank readonly required fields. As well, it doesn't seem to remove the invalid setting when I change the field to readonly through JavaScript. Am I missing something, or is this just something specific to my product's implementation of this? – Brisbe May 30 '12 at 20:06
  • Just to explain what had happened, this did work for me--to a point. My code had some hidden features that made it start the page with validation errors already applied server-side. I ended up having to go with a solution that affected these. The .valid() on the items, combined with flipping the readonly flag, worked for the client-side validation. Thanks for the help! – Brisbe Jun 06 '12 at 18:11