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 (Ajaxally, 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:
$('#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:
{“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.
{“type”: “continue”, “label”, “request_detail.php”} |
You can also send parameters to the url using the “params” option.
{“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:
location.href = ‘request_detail.php?name=doAdd&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:
ajax_success: {listener: "frmLogin", func: [ {name : "goTo", params: [ {param: ‘request_detail.php?name=doAdd&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
function registration() { this.regComplete = function() { }; } |
So the ajax_success option will look like this:
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:
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.
[{“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:
{"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:
"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.
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).
{"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.
{"id": "age", "label": "Age", "rules": [{"name": "meetsCondition", “value”: “21”, “condition”: “>=”}] } |
The plugin can be downloaded from Google Code or JQuery Plugins
Click here to view examples of using the imValidateForm plugin.


[...] User Interface Library (YUI), the more I am impressed with it. I have been converting my JQuery imValidateForm plugin to a YUI widget for a project that I am working on. I ran into a scope issue when a button [...]
Question: I have a form that requires the user to fill in two of 4 separate text fields in order to successfully submit the form. What I need to do is have it validate if either the first two or the second two fields are both filled in, and then display an error message if the user has not filled in either both of the first two or both of the second two…..is this possible using eitherOr? Thanks for any help you might be able to offer me on this!
No, eitherOr can not handle that type of situation. Sorry.
hi! this is a really useful plugin. Maybe I didn’t see, but can you please post a php/asp example of the server side processing. For example, json resulting text must be [ {"message", "It's all good"} ] ?
I created demos for all my JQuery Plugins – http://grasshopperpebbles.com/demos/
I will be adding my YUI and Dojo widgets here as well (as soon as I get the time).
Thanks for the plugin, hope you can help me with a problem I have.
If I hit the submit button while any “watched” field is empty, the plugin throws an error message to my reporting div section.
However, if I attempt to submit the form again I receive this message in my reporting div section:
“[object Object]”
Any subsequent submission attempts fail and the page is neither submitted or refreshed.
I should also mention that I am using code from “SPAM Protection Using PHP and jQuery”
http://plugins.jquery.com/project/SPAMProtection
Here is my jQuery code:
jQuery(“.required”).blur(function() {
jQuery.get(“newregister.php”, { //name of the PHP file containing the session code
confirm: ”
},
function(data){
// alert(“Data Loaded: ” + data);
});
});
jQuery(“#btnSubmit”).click(function() {
jQuery(“#form1″).imValidateForm({
responseDiv: ‘response’,
validate_map: valMapReg1,
url:’newregister.php’,
data_type: ‘text’,
submit_button: ‘btnSubmit’
});
return false;
});
The page is not posted yet, so I will provide more code if asked or needed.
I was able to duplicate your problem. I’m surprised no one else caught it. I put a new version (1.2) on both JQuery’s plugin site and Google Code (http://code.google.com/p/imvalidateform/). Thanks.
Wow, awesome! Thank you.
Apparently I can’t figure out how to add actual HTML to this comment….
I’m trying to use imValidateForm from within some PHP code. When I click Submit I see that it gets called, because the Submit button becomes unavailable, but I never get any error messages and if there are no errors in the form, the url never gets called. I’m using jQuery 1.3.2. In my PHP I have:
$(document).ready( function( ) {
$(‘#submit’).click( function( ) {
$(‘#frmRequest’).imValidateForm( {
responseDiv: ‘response’,
validate_func: ‘validateFields’,
validate_map: valMapReg1,
url: ‘request.php’,
data_type: ‘json’,
submit_button: ‘submit’
} );
return false;
} );
} );
And my validation map looks like:
var valMapReg1 = { “fields”: [
{"id": "pi_name", "label": "Principal Investigator", "rules": [{"name": "hasValue", "exclude": "0"}]},
{“id”: “title”, “label”: “Title”, “rules”: [{"name": "hasValue"}]},
{“id”: “discipline”, “label”: “Scientific Discipline”, “rules”: [{"name": "hasValue"}]},
{“id”: “area”, “label”: “Disciplinary Area”, “rules”: [{"name": "hasValue", "exclude": "0"}]},
{“id”: “abstract”, “label”: “Abstract”, “rules”: [{"name": "hasValue"}]},
{“id”: “tos”, “label”: “Terms of Service”, “rules”: [{"name": "isChecked"}]}
]}
Just got back into town. Did you place the document.ready function within ?
The document.ready function is in the <head> section enclosed in <script type=”text/javascript”> <script> tags.