27 Jan 2014

JQuery Conditional Validation (Yes, the official documentation sucks)

Venting! jQuery Validation is a great plugin but its documentation is crap! So much cool stuff is hidden away for want of decent docs. If enough of you agree with me, I might have to write some! Watch this space. 

Anyway, I just wanted to implement some conditional validation

i.e. MAKE INPUT 'A' REQUIRED ONLY IF INPUT 'B' HAS A VALUE

And so, given two inputs with IDs InputA and InputB, the code is:

    
$(function() {
 $('#YourForm').validate({
  rules: {
   InputA : { 
    required : '#InputB:filled'
   }
  }
 });
});

You can also do this inline in your form by using declarative syntax, which I have found bugger-all documenation on!
 
<input name="InputA" type="text" data-rule-required="#InputB:filled" />
<input name="InputB" id="InputB" type="text" />

Finally, when required status is dependent on something more complicated, you can throw in a function e.g.
 
$('#myForm').validate({
 rules: {
  InputA : {
        required: function (elem) {
              // InputA is required if InputB contains 'AmazingThingy'
              return $('#InputB').val() == 'AmazingThingy';
   }
  }
 }
});

1 comment:

  1. Anonymous4:31 pm

    I totally agree! The documentation is awful for a script which is so good. I am prepared to bet that a lot of new developers give up on it before they realise how good it is because one could easily assume it doesn't have the most basic of features simply because the documentation fails to list them anywhere.

    ReplyDelete

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!