jQuery Validator Plugin with a Custom Validation Function and Dependency Selectors

The jQuery validator plugin is a great way to add validation to forms in a clean way.  Error messages shown and hidden when they attempt to submit, and on the fly when they correct the input.

I recently added a new validation function to see if the field they entered was a valid twitter hashtag or username.  Though it could be improved (ie. looking for spaces), it does the job initially.  The problem was that the same field name was used for both depending on the value of another dropdown.

To handle enabling or disabling the validation function based on a certain condition, I initially thought you just pass in true or false, such as you do with required:

jQuery('#socialAdminForm').validate({
    rules: {
        component: { twitteruserrequired: true }
    }
    // ...

However the the 3rd parameter (which I’ve labelled, ‘isactive’) needs to be evaluated based on the condition, as the boolean value is passed in here. Here’s an example that determines whether or not to use the validation function based on the select element with id wx-select-social:

jQuery.validator.addMethod('twitteruserrequired', function(value, element, isactive) {
    return !isactive || (value.trim() != '@' && value.substr(0, 1) == '@');
}, "Please enter a valid value");

jQuery.validator.addMethod('twitterhashtagrequired', function(value, element, isactive) {
    return !isactive || (value.trim() != '#' && value.substr(0, 1) == '#');
}, "Please enter a valid value");

jQuery('#socialAdminForm').validate({
    rules: {
        component: { required: true },
        name: { required: true },
        "component_behaviour": { required: true, twitteruserrequired: function(element) {
                return (jQuery("select#wx-select-social").val() == 'twitteruser');
            }, twitterhashtagrequired: function(element) {
                return (jQuery("select#wx-select-social").val() == 'twitterhashtag');
            }
        } }
    }
    // ...

Without the third parameter of the function in addMethod being evaluated for true or false, the validation function will always execute.