1
votes

I am using the jQuery Validation Plugin to validate a number of inputs on a html page. The first name is always required, and either email OR mobile but not both. To do this, I use the require_from_group_exact method.

When the inputs are in this order, validation occurs perfectly:

<form>
  Email: <input class="commsinfo" name="email"><br>
  Mobile: <input class="commsinfo" name="mobile"><br>
  Name: <input name="firstname"><br>
  <input type="submit">
</form>

However if you swap the inputs around, validation of the last input (firstname) does not occur properly (you have to type a firstname and then delete it to trigger validation) - why??. This is the desired order and issue I'm trying to solve - is it a bug with the jQuery Validation Plugin or my code?

<form>
  Name: <input name="firstname"><br>
  Email: <input class="commsinfo" name="email"><br>
  Mobile: <input class="commsinfo" name="mobile"><br>
  <input type="submit">
</form>

I have created a JSFiddle of the version the does not validate properly. The code for the jQuery.validator.addMethod and $('form').validate can be seen in the fiddle.

3

3 Answers

1
votes

You're not checking all the input fields,

change var fields = $(selector, element.form);

to var fields = $('form :input');

Updated Fiddle

1
votes

In the example you've provided, there seems to be an issue with the call to fields.valid().

I've updated the fiddle to remove some code I don't think you need. The call to valid() seems to be the crux of the problem and removing it causes the validation to work as expected.

The updated code now looks like this:

jQuery.validator.addMethod("require_from_group_exact", function(value, element, options) {
  var validator = this;
  var selector = options[1];
  var validOrNot = $(selector, element.form).filter(function() {
    return validator.elementValue(this);
  }).length == options[0];

  return validOrNot;
}, jQuery.format("Please fill {0} of these fields."));

$('form').validate({
  rules: {
    firstname: { required: true },
    email: { require_from_group_exact: [1, ".commsinfo"] },
    mobile: { require_from_group_exact: [1, ".commsinfo"] },
  }
});

Updated Fiddle

0
votes

Every time you call the

fields.valid();

your validator method is recalled and so you get the apparently strange behaviour. You can check this debugging by yourself.