JQuery Plugin: imValidateForm

Prior to using JQuery, I had developed Javascript object that validated forms prior to submission. I got the basic concept (and some code) from the book, “Beginning Ajax with PHP: From Novice to Professional” by Lee Babin. I modified it a great deal. Once I began using JQuery, I converted the Javascript object to a JQuery plugin. Unlike most validation plugins which validate input on exit of the field (onBlur), the imValidateForm plugin validates the entire form once the user clicks the submit button. The plugin also handles the submission (, of course) and allows you to disable the submit button to prevent double-clicking.

The imValidate plugin will validate the following:

Required Fields/Exclude Values
Valid Email
Either/Or (Either input 1 or input 2 must be entered)
Valid values (Must be equal to)
Checked Values (is the field checked)
Is Numeric
Is Alpha Only
Meets Condition (==, !=, <, <=, >, >=)

Instantiation of the plugin is as follows:

?View Code JAVASCRIPT
$('#bSubmit’).click(function() {
         $('#frmJoin”).imValidateForm({
                  responseDiv:  ‘response’,
                  //optional
                  validate_func: ‘validateFields’,
                  validate_map: valMapRequestor,
                  url: 'includes/controllers/dbActionController.php'
                  //optional
                  data_type: 'json',
                  //optional
                  ajax_success: showMessage,
                  //optional
                  complete: '',
                  //optional
                  submit_button: ‘bSubmit’
        });
        return false;
});

Options

Note: The descriptions of the options listed below are not listed in the order that they appear in the plugin invocation example above. Also, notice the ‘return false’ in the code above. It is very important with Ajax submissions. Click here to read more.

#frmJoin: The ‘id’ of the form that will be submitted.

submit_button: Use this option if you want the form’s submit button to be disabled after the user clicks once. This prevents the double-clicking. The button is then enabled upon a successful submission.

responseDiv: This is div that will display either the error message (if validation fails) or the response that comes back from the server.

validate_func: This is optional. I created this option in the event that I create other methods for this plugin in the future. The default is “validateFields”. The “validateFields” method is called when the submit button is clicked. It begins the form validation process. In the future, I may add an ‘onExit’ and/or other methods.

url: Form action. The url where the form will be submitted.

data_type: This is the expected data type that will be returned from the server. The default value is ‘json’. The plugin has a built-in method (showMessage) that handles the ajax response (displays the message in the responseDiv). If you plan to use the showMessage method, the data type for the response must be either ‘json’ or ‘text’. If you plan to return a response that is not ‘json’ or ‘text’, you must use the ‘complete’ method. Then the data type value must be one the data types expected from JQuery’s Ajax method (‘json’, ‘xml’, ‘html’, ‘script’, ‘jsonp’, ‘text’).

complete: This is optional. If you plan to return a data type that is ‘xml’, ‘html’, ‘script’ or ‘jsonp’, use this option to call the function that handle the processing. I just recently added this option, but I don’t think that it will be used that often. The function that is called must be a method within a Javascript object (more on this below).

ajax_success: This is optional. ‘showMessage’ will be called by default upon a successful submission. In order to use the ‘showMessage’ method, the data type returned from the server must be ‘json’ or ‘text’. If it is ‘json’, it must have the following format:

?View Code JAVASCRIPT
{“type”: “message”, “label”, “Form submitted successfully”}

The plugin first looks at “type”. If “type” == “message”, then the responseDiv will display the “label” value. “Type” can alternatively have a value of “continue”. Then the label value should be the url that you want the user to go to upon a successful submission.

?View Code JAVASCRIPT
{“type”:continue, “label”, “request_detail.php}

You can also send parameters to the url using the “params” option.

?View Code JAVASCRIPT
{“type”:continue, “label”, “request_detail.php, “params”: [
{name: “action”, “value”: “doAdd”}, {name: “reqID”, “value”:20}]}

In the example above, the imValidateForm plugin will create the following:

?View Code JAVASCRIPT
location.href = ‘request_detail.php?name=doAdd&amp;reqID=20

The only time you really need to use the ‘ajax_success’ method is if you want to override the default behavior. For instance, if you prefer to control the location in your client-side code, you can alternatively use the ajax_success option as follows:

?View Code JAVASCRIPT
ajax_success: {listener: "frmLogin", func: [
         {name : "goTo", params: [
                    {param: ‘request_detail.php?name=doAdd&amp;reqID=20}]
         }
]}

‘goTo’ is the only built-in method when overriding the default ‘ajax_success’ behavior, but you can call any function that you create. If you do not use the ‘goTo’ function, then function you call must be a method within a Javascript object (see below for more details).

listener: The element that you want to listen for the server response. This is usually the form, but can be any element that you want.

name: The name of the function that you want to call. If not using the ‘goTo’ function, then the function must be a method within a Javascript object.

param: Any parameters that you want sent to the function.

In order to call you own function, you must first set up a Javascript Object

?View Code JAVASCRIPT
function registration() {
         this.regComplete = function() {
 
         };
}

So the ajax_success option will look like this:

?View Code JAVASCRIPT
ajax_success: {listener: "frmRegistration", func: [
         {name : registration.regComplete}]
}

The Validation Map

validate_map: The rules for each field in the form must be stored as a Json object. The imValidate plugin uses these rules to validate the form. I usually store all Json objects for every form within an application in a separate (single) Javascript file. The Json object maps every field that is to be validated to a specific validation rule. Multiple rules can be applied to each field. The following is a typical validation object:

?View Code JAVASCRIPT
var valMapRequestor = { "fields":
	[{"id": "tFirstName", "label" : "First Name", "rules":
                                                       [{"name": "hasValue"}]
                                                         },
         {"id": "tLastName", "label": "Last Name", "rules":
                                                       [{"name": "hasValue"}]
                                                        },
         {"id": "tAddress1", "label": "Street Address", "rules":
                                                       [{"name": "eitherOr", "fields": [
                                                                                  {"id" : "tAddress2"}]}]
                                                        },
         {"id": "tCity", "label": "City", "rules":
                                                       [{"name": "hasValue"}]
                                                        },
         {"id": "tZipCode", "label": "Zip Code", "rules":
                                                       [{"name": "hasValue"}, {"name": "isNum"}]
                                                        },
         {"id": "cbxReferredBy", "label": "ReferredBy", "rules":
                                                       [{"name": "hasValue"}]
                                                        },
         {"id": "rdoGender", "label": "Gender", "rules":
                                                       [{"name": "isChecked", "fields": [
                                                                        {"id" : "rdoGender"}]}]
                                                        },
         {"id": "rdoResident", "label": "Resident", "rules":
                                                        [{"name": "isChecked", "fields": [
                                                                        {"id" : "rdoResident"}]}]
                                                        },
         {"id": "rdoInsurance", "label": "Insurance", "rules":
                                                        [{"name": "isChecked", "fields": [
                                                                        {"id" : "rdoInsurance"}]}]
                                                        }]
}

id: The id of the field that is to be validated. Again, the Json object should only contain the fields in the form that are to be validated.

label: The label is the text of the field name that you want to display if an error occurs (“First Name” can’t be blank).

rules: These are the validation rules that will be applied to a field. Again, multiple rules can be applied. The rules should be formatted as Json Members (link). The “name” is the name of the rule that is coded in the imValidateForm plugin. As with any Json object, multiple members should be separated with commas.

?View Code JAVASCRIPT
[{name: “hasValue”},  {name: “isNum”}]

The rule names are as follows:

hasValue: This rule validates required fields, but you can also use it to exclude a value. I added this extension to the rule for situations when an input field has a default value that you do not want submitted to your backend.

<input id="first_name" name="first_name" type=”text" value="Enter" />

I don’t want “Enter First Name” submitted to the database, so I create the rule:

?View Code JAVASCRIPT
{"id": "first_name", "label" : "First Name", "rules":
                                          [{"name": "hasValue", “exclude”: “Enter First Name}
}

isValidEmail: Validates if an email has the correct format
eitherOr: Either/Or (Either input 1 or input 2 must be entered). Look at “tAddress1” in the code above to view an example of this rule. You must provide the “id” of each field that is to be evaluated, using the format:

?View Code JAVASCRIPT
"fields" : [ {“id”: “Field ID”}]

isEqual: Use this rule when multiple fields in a form need to have the same value. A typical situation in which this can occur is when you have two password fields in a form (the first is the actual password that is submitted to the database, the other field will be used to verify that the password that a user entered is what they intended). As with the “eitherOr” rule, the “id” of the field that is to be evaluated must be provided.

?View Code JAVASCRIPT
var valMapPassReset = { "fields":
            [{"id": "tPassword", "label": "Password", "rules":
                                                        [{"name": "hasValue"}, {"name": "isEqual", "fields": [
                                                                                                        {"id" : "tPassCheck"}]}]
            }]
}

isChecked: Checks whether the field is checked (checkboxes and radio buttons). As with the “isEqual” and “eitherOr” rules, this rule must be supplied the “id” of the field that is to be evaluated. If you enter “all” as the “id”, the plugin will check the entire form to see if at least one field in the form is checked. I created this option when I ran into a situation where I created a form that contained nothing but checkboxes and at least one of the checkboxes had to be selected in order to submit the form (see imCheckBoxDB).

?View Code JAVASCRIPT
{"id": "chb_1", "label": "Music Event", "rules":
                                         [{"name": "isChecked", "fields": [
                                                                     {"id" : "all"}]}]
}

isNum: Checks whether the field is a number.
isAlpha: Checks for alphabetic characters only.
isAlphaNumeric: Checks for alphabetic and numeric characters only.
meetsCondition: The value of the field must meet a particular condition. You must supply a value and the comparison operator to be used (==, !=, <, <=, >, >=). In the example below, the “age” field must be greater than or equal to 21.

?View Code JAVASCRIPT
{"id": "age", "label": "Age", "rules":
                              [{"name": "meetsCondition", “value”:21, “condition”:&gt;=}]
}

The plugin can be downloaded from Google Code or JQuery Plugins

Click here to view examples of using the imValidateForm plugin.

Be Sociable, Share!
Adjective: Meaning to post or retrieve information without having to refresh the page
Note: This is totally made up!! Perhaps I should add it to wikipedia or trademark the word!!

Checkout My New Site - T-shirts For Geeks