4

I have a form with the following two HTML elements:

<input type="text" name="vrm" id="vrm" size="15" maxlength="15" value="" />
<input type="checkbox" id="foreign_registration" name="foreign_registration" value="yes" />

and the following jQuery validation rule (using the validation plugin from here: http://bassistance.de/jquery-plugins/jquery-plugin-validation/):

vrm: {
       remote: {
            url: "/json/vrm-validate.php",
            data: {
              foreign_registration: function() {
                return $('#foreign_registration').is(':checked');
              }
            }
          }
        }

The remote script relies on both fields, as the validation performed on the text field depends on whether the foreign registration is checked or not.

The problem is that if I enter something in the text field and then alter the checkbox, the validation rule isn't re-run. I presume that this is because the validation rule is only attached to the text field, so it will only run whenever that is changed.

Is there a way to say 'these two elements are related, so if either of them change assume that the text field rules should be checked again'? I don't want to attach any validation rules to the checkbox, because it doesn't need to be validated on the client side, and the validation rules performed by the remote script are too complicated to implement in jQuery.

pwaring
  • 3,032
  • 8
  • 30
  • 46

2 Answers2

6

An alternative answer which I was sent by email is:

isOI is my checkbox and Item is my textbox that I need to revalidate when the checkbox is clicked.

$("#isOI").change(function () {
  var item = $("#Item");
  item.data("previousValue", null).valid();
});

Apparently the existing answer didn't work for this person.

pwaring
  • 3,032
  • 8
  • 30
  • 46
  • This method forces the field to re-validate. Otherwise, if the value of the field itself hasn't changed, it will not re-validate. – Super Scary Apr 20 '18 at 16:29
  • 1
    That's exactly what I want - forcing field A to revalidate when field B changes, even if field A does not change. – pwaring May 08 '18 at 08:56
1

you could call the validate function on the change of the checkbox

$(':checkbox').change(function(){
    $('form').validate();
});
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Qpirate
  • 2,078
  • 1
  • 29
  • 41
  • Won't that revalidate the whole form though? I only really want to validate the text field, especially as the form will probably grow over time. – pwaring May 29 '12 at 09:08
  • yes it will after doin a quick search i found this http://stackoverflow.com/q/2738925/801241 it may help in what you wish to do. – Qpirate May 29 '12 at 09:12