A jQuery inline form validation, because validation is a mess

When it comes to form validation, it’s hard to have a versatile solution that works with every form. Figuring out how to display errors is not a simple task. This is something I tried to remedy with this script. When an error needs to be displayed, the script creates a div and positions it in the top right corner of the input. This way you don’t have to worry about your HTML form structure. The rounded corner and shadow are done with CSS3 and degrade well in non compliant browsers. There is no images needed.

When you submit a form, it will look for inputs with predefined class selectors, and validate them accordingly to their type. It also does on the fly validation when you click outside of the input. When validating on submit , every errors will appear in absolute position above the input in question, and slide the scroll bar to this first error (diminish your browser window if you don’t see the effect).

The on the fly validation will validate the modified input when you click outside of the text zone.

View demo

(With ajax submit)
View demo

Coming in v1.4
Ajax validation (ex: looking if user name is available in a db)
Use validation function outside of the plugin (calling it directly in JavaScript)
Use prompt function outside of the plugin (calling it directly in JavaScript)
Prompt Positionning
Ajax submitted form

More compatibility with frameworks
Minor bugfixes

Localisation language is also available, I already did a (poor) french localisation. Do not include more than one localization at a time in a page. Custom regEx rules with error messages can also be added very easily for you crazy guys that understand how regEx rules actually work.

Get this to work

First add the jquery library and the jquery.validationEngine.js and css to your head.

      
      

When this is done, you need to call the form you want to validate. I use an ID but you could use a class too.

      $(document).ready(function() {
       $("#formID").validationEngine({
        inlineValidation: false,
        success :  false,
        failure : function() { callFailFunction()  }
       })
      })

After you need to add a class on the input you want to validate, you can stack as much rules as you want.


Here are the rules already implemented in the validator:

optional: Special: Only validate when the field is not empty *Please call optional first
required: Field is required
length[0,100] : Between x and x characters allowed
minCheckbox[7] : Set the maximum checkbox autorized for a group
confirm[fieldID] : Match the other field (ie:confirm password)
telephone : Match telephone regEx rule.
email : Match email regEx rule.
onlyNumber : Numbers only
noSpecialCaracters : No special characters allowed
onlyLetter : Letters only
date : Invalid date, must be in YYYY-MM-DD format
Customizations

Custom RegEx Rules:
You can create custom rules easily, only add your custom rule in the json object, you can take telephone as an example, just copy and paste under it.

      "telephone":{
      "regex":"/^[0-9-()]+$/",
      "alertText":"* Invalid phone number"},

Language localization:
In the js folder you will find jquery.validationEngine-fr.js , in this file you have the json object used to create the validation rules, you can localize this file in any language you like. Add this file just before jquery.validationEngine.js. Your head document should look like this:


      
      
      

Optional inline validation
You can now validate only on form submit by using this customization: inlineValidation: false, in your DOM ready,

      $("#formID").validationEngine({
      inlineValidation: false,
      success :  false,
      failure : function() { callFailFunction()  }
      })

Prompt positioning
Positioning is not perfect, this is a good start but much work is needed to have this working in every situation, when you call on dom ready change this setting.

      $("#formID").validationEngine({
      promptPosition: "topRight", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft,  centerRight, bottomRight
      success :  false,
      failure : function() {
      })

I want to validate directly from javascript
You can call a validation like this: $.validationEngine.loadValidation(”#date”)

Open and close prompts on everything
Use my prompt on everything you want like a div element. You can call a prompt this way: $.validationEngine.buildPrompt(#ID,promptMessage,type)
ex: $.validationEngine.buildPrompt(”#date”,”This field is required”,”error”)

Close prompt for field ID: $.validationEngine.closePrompt(”#date”)
Close prompt anything else: $.validationEngine.closePrompt(”.allmydiv”,true) true means look outside the form
There are 3 type : error (red), pass (green), loading (black)

Stop inline validation for 1 field
Sometimes you have a field with a calender, but you want to keep the inline validation for all the other fields, or even this field if the user manually change the input. Well you can now intercept the inline validation by setting this variable on onlick or onchange state : $.validationEngine.intercept = true;
Inline AJAX validation

This functionality is quite simple to integrate, in your class attribute add: ajax[ajaxUser]
It should be the last item to validate in your validate[], while this is not necessary, I found it worked best there.
Ajax validation works only inline, when your field is validated for normal rules, it will create a post to a php file. There is no way for the user to bypass this, if the field do not validate on form submit, the user will need to change the information and the AJAX validation will occur.

In your json you follow pretty much the same syntax that you would use with a custom regex:

“ajaxUser”:{
“file”:”validateUser.php”,
“alertText”:”* This user is already taken”,
“alertTextOk”:”* This user is available”,
“alertTextLoad”:”* Loading please wait”},

The “file”: is obviously where you want your field value to be posted. In the validateUser.php you will have to keep the defined variable at the top, do your validation and at the end of the file you will see that I echo a json variable back. Please keep the same syntax. For now this file fake a php validation.

The alertTextOk and alertTextLoad are optional, this is, for example, to tell your user the nickname he has chosen is available, the box will also become green.
Ajax Submitting

This send your form to a specific php file for manipulation, you can return field errors or a success text message. The ajax success function described below can still be called and will be executed after the ajax submit validation occur.

      $("#formID").validationEngine({
       ajaxSubmit: true,
        ajaxSubmitFile: "ajaxSubmit.php",
        ajaxSubmitMessage: "Thank you, we received your inscription!",
       success :  false,
       failure : function() {}
      })

In your php, if the form validate, the variable $isValidate need to be set to true the form will disappear and the success message will appear instead. If it does not validate set $isValidate to false follow this syntax to call an array of errors :

      $arrayError[0][0] = "#email";   // FIELDID
      $arrayError[0][1] = "Your email do not match.. whatever it need to match";  // TEXT ERROR
      $arrayError[0][2] = "error";   // BOX COLOR

AJAX Success and failure call to actions
If you want to post your form in AJAX you can define a success and failure function to be executed on form submit and there will be no page reload. In the jquery.validationEngine.js. Look in the document ready for this:

      // replace "success: false," by: success : function() { callSuccessFunction() },
      $("#formID").validationEngine({
      success :  false,
      failure : function() { callFailFunction()  }
      })

UPDATE: This version break compatibility with the older versions, I would suggest to be very careful if you are updating, you need an id attribut on every input you validate!

Download the source code View demo

Tested on:
Internet Exploder 6 & 7
Firefox 3+
Safari 4
Chrome 1+

Version 1.3.9.6 Online
August 25, release v.1.3.9.6: Ajax submit, prompt positioning, bug correction with multiple forms
August 13, release v.1.3: Ajax validation, prompts usable outside the plugin, minor CSS corrections
July 12, release v.1.3: Validation with ids instead of name, minor CSS corrections, optional inline validation.
June 5, release v.1.2.1: Added optional validation
June 5, release v.1.2: Less error prone reg Ex, corrected an error with multiple form on the same page
June 4, release v.1.1: added date validation and select required validation, corrected errors with group radio input
June 1, release v.1.0

If you like and use this script, please consider buying me a beer, it’s cheap and a simple way to give back!
source :: position-absolute

دیدگاه خود را بفرستید