jQuery Validator: Adding a Custom Method

File this one under “Posted to take less time to find the answer”:

If you’re using jQuery Validator and the built in validation methods just aren’t cutting, there’s a way you can add your own method to the validator itself. For this example let’s start some pretend time. Uhg I said pretend time not f–ked up fantasy time… Really, a horse? Really?

Now that we have that clear: Let’s pretend you have a form with three textboxes and you want to make sure one and only one is filled out. This doesn’t exactly fit the built in methods. Now you could try using the “required” method and replace it with a delegate. Could do that, but it ‘s  actually trickier than it sounds due to how required method actually works.  So what’s an easier way? Just add a method to the validator:

    jQuery.validator.addMethod('correctCountFilled', function(value, element) {
        var fullCount = 0;
        if(jQuery('#someTextBox1').val().length > 0){
            fullCount +=1;
        }

        if(jQuery('#someTextBox2').val().length > 0){
            fullCount +=1;
        }

        if(jQuery('#someTextBox3').val().length > 0){
            fullCount +=1;
        }

        return fullCount == 1;
    });

Then the call is done lika dis:

  ...

  rules: {
            someTextBox1: {
                correctCountFilled:  true  //This is the name of the method added and what it expects to come back when called to be valid.
            }
        },
  messages: {
            someTextBox1: {
                correctCountFilled: 'Some error message like pointing out how yours is a superior intellect.'
            }
        },
  ...

As you can see, the method returns false if all are empty or more than one is filled in. The method call on the validator expects “true” to be valid, so anything but one textbox being filled in will trigger the error message. Fairly easy, huh? Now go forth, be fruitful, and don’t multiply by mistake.

2 thoughts on “jQuery Validator: Adding a Custom Method”

  1. You did some topic on Multiple checkBoc handling. Can you do a complete validation exemple with at least one checkbox checked.

Comments are closed.