May
30

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.

Download the source code View demo

(With ajax submit)
View demo

(With overflown hidden parent)
View demo

Please report issues in the google code project
More informations about how to integrate it with the asp.net MVC framework

Coming in v1.8
Window Resize

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, js language and css to your head.

  1. <link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" charset="utf-8" />
  2. <script src="js/jquery.js" type="text/javascript"></script>
  3. <script src="js/jquery.validationEngine-en.js" type="text/javascript"></script>
  4. <script src="js/jquery.validationEngine.js" type="text/javascript"></script>

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.

  1. $(document).ready(function() {
  2.  $("#formID").validationEngine()
  3. })

After you need to add a class on the input you want to validate, you can stack as much rules as you want. If you use multiple class on the input please put validate[] rules first.

  1. <input class="validate[required,custom[onlyLetter],length[0,100]]" name="firstname" type="text" />

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
maxCheckbox[7] : Set the maximum checkbox autorized for a group
minCheckbox[7] : Set the minimum 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
exemptString : Will not validate if the string match
date : Invalid date, must be in YYYY-MM-DD format
funcCall : Validate custom functions outside of the engine scope

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.

  1. "telephone":{
  2. "regex":"/^[0-9-()]+$/",
  3. "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:

  1. <link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" charset="utf-8" />
  2. <script src="js/jquery.js" type="text/javascript"></script>
  3. <script src="js/jquery.validationEngine-fr.js" type="text/javascript"></script>
  4. <script src="js/jquery.validationEngine.js" type="text/javascript"></script>

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

  1. $("#formID").validationEngine({
  2. inlineValidation: false,
  3. success :  false,
  4. failure : function() { callFailFunction()  }
  5. })

Change validation event trigger
You can change the event that trigger the validation in the settings, default is blur

  1. $("#formID").validationEngine({
  2. validationEventTriggers:"keyup blur",  //will validate on keyup and blur  
  3. success :  false,
  4. failure : function() { callFailFunction()  }
  5. })

No scrolling

  1.  $("#formID").validationEngine({scroll:false})

Validate and return true or false
Can be use anywhere in your script

  1. alert($("#formID").validationEngine({returnIsValid:true}));  // alert will return true or false

Do not unbind the engine submit event upon success function
You may not need this setting, sometimes you want the engine to stay binded on submit even if the success function is fired.

  1. $("#formID").validationEngine({unbindEngine:false}));

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.

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

Custom functions call (Validate from any function you created)

Sometimes you need to validate complex rules that are not included in this engine. With this feature you can validate from any function in javascript and return true if there is and error and false if the function validate correctly.

In your field add:

  1. <input value=""  class="validate[required,funcCall[validate2fields]] text-input" type="text" id="lastname" name="lastname"  />

In your language js file have something like (nname is the function name to call):

  1. "validate2fields":{
  2.          "nname":"validate2fields",
  3.          "alertText":"* You must have a firstname and a lastname"}
  4.      }

Now the custom function that could be anywhere in your JS

  1.  function validate2fields(){
  2.    if($("#firstname").val() =="" || $("#lastname").val() == ""){
  3.     return true;
  4.    }else{
  5.     return false;
  6.    }
  7.   }

Validation in overflown div and lightbox with scrollable content

To get the supported mode you need to add these options when instancing your plugin:

  1. $("#formID").validationEngine({
  2.  containerOverflow:true,  // Enable Overflown mode
  3.  containerOverflowDOM:"#divOverflown"  // The actual DOM element container with overflow scroll on it
  4. })

The big change in this method is that normally the engine will append every error boxes to the body. In this case it will append every error boxes before the input validated. This add a bit of complexity, if you want the error box to behave correctly you need to wrap the input in a div being position relative, and exactly wrapping the input width and height. The easiest way to do that is by adding float:left, like in the example provided.

The default top right position is currently the only supported position. Please use this mode only in overflown div and in scollable boxes, it is slower and a bit less stable (I have been using the engine for 2 years, but only one 1 month with this method). Also, the scrolling will be applied to the overflown parent, not the document body.

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.

Extra Data

You can add extra data to apss along with this setting: ajaxSubmitExtraData

  1. $("#formID").validationEngine({
  2.  ajaxSubmit: true,
  3.   ajaxSubmitFile: "ajaxSubmit.php",
  4.   ajaxSubmitMessage: "Thank you, we received your inscription!",
  5.                 ajaxSubmitExtraData: "securityCode=38709238423&name=john",
  6.  success :  false,
  7.  failure : function() {}
  8. })

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 :

  1. $arrayError[0][0] = "#email";   // FIELDID
  2. $arrayError[0][1] = "Your email do not match.. whatever it need to match";  // TEXT ERROR
  3. $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:

  1. // replace "success: false," by: success : function() { callSuccessFunction() },
  2.  
  3. $("#formID").validationEngine({
  4. success :  false,
  5. failure : function() { callFailFunction()  }
  6. })

Debug Mode

The debug mode appears when there is something wrong with the validation engine. It has a set of trigger to look upon validation and try to help you accordingly, it should help you get everything in line to get the script working in your environment.


STABLE with jQuery 1.4.2

Download the source code View demo

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

Download the older version, STABLE with jQuery 1.3.2 1.6.2



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


Version 1.7 Online
July 1 2010, release v1.7: div overflown support + small fix to inline ajax validation + small code overhaul
Feb 1 2010, release v.1.6.3: bugfixs from forum + exempString rule addition, update to jQuery 1.4
November 23, release v.1.6.2: bugfix script loaded via ajax,
November 23, release v.1.6.1: Refactoring, external loadvalidation() is back working, languages are now ALL loaded externally, added setting to not unbind form on success,
October 29, release v.1.6: unbind validation when success function is called, option returnIsValid added
October 27, release v.1.5: Added debug mode, event triggerer can be specified in setting and checkbox bug with cakephp corrected
September 17, release v.1.4: More frameworks support, changes with the minCheckbox and maxCheckbox
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

Comments are closed due to the overwhelming number, please use the forums for support.

491 Comments to “A jQuery inline form validation, because validation is a mess”

  • I had implement validation and datepicker but both not working.only at time one working if another one in comment.please give solution

  • [...] A jQuery inline form validation, because validation is a mess [...]

  • Hi Cedric,

    Do you plan on making your script to use multiple forms on a single page?

    Thanks!

  • Next version coming soon is form based instead of being called class based, this is not coming this week, I have 2 project dealine

  • It don’t work with complex name such as customer[address], Can you please advice me

  • This line:

    if(!$(“select[name="+callerName+"]“).val()) {

    should be:

    if(!$(“select[id="+callerName+"]“).val()) {

    Since we’re using id’s instead of names for everything else. And for me, my name was different than the id.. I couldn’t figure out why it would never validate :) Great class!

  • Hi Cedric,
    great plugin! Really easy on the eye as well.
    I’ve run into a problem with the regular expressions, in that they weren’t really working! The RE strings are specified as a plain string, meaning that all ‘\’ backslashes will disappear, and will not end up in the final regular expression (after eval). I ran into this because my email field would not catch “dude@there” although the regexp was correct. After double-escaping everything works as expected. So instead of \. for a literal dot, it should be \\.
    I made the change for all regexps and on my side everything works correctly now.

  • thanks for the comment I will add this in the next version

  • Excellent plug-in! Is there a way to disable/enable the validation? I have two forms that are both contained in the same form tag. I have to do this because I am using ASP with codebehind and you can only have one runat=”server” form.

  • Je suppose que tu parle français donc je le dit en FR :D

    il y a un problème avec le script, ce qui marche bien chez toi ne marche pas chez d’autre (c’est bizarre) j’ai Jquery 1.3.2 et la dernière version de ton script et J’ai une erreur dès la première ligne!
    Enfait :

    “$(document).ready(function() …” n’est pas reconnu alors j’ai remplacer par ce que j’utilise d’habitude à savoir …
    “jQuery(document).ready(function($) …” Et ça remarche mais je ne sais pas pourquoi ça ne marche pas comme sur la demo !

  • Cela arrive quand tu utilise plus qu’un librairie en general

  • [...] A jQuery inline form validation, because validation is a mess Të Position AbsoluteWhen 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. [...]

  • Nice! Thank you

  • Nice plugin.

    Question:

    I’m having problems with the Ajax validator when checking mysql database. I keep getting “This user is already taken”.

    I’ve edited the mysql database call in validateUser.php with my database info
    I replaced function, as you suggested, in jquery.validationEngine.js to…

    callSuccessFunction() },
    $(“[class^=validate]“).validationEngine({
    success : function() { callSuccessFunction() },
    failure : function() {}
    })

    Even in your demo form I keep getting the same alert.

    Is there a work around on this issue?

    Thanks again.

  • I need help how can i do this example:
    there is name, surname and address field. If user fill one of them he must fill others too.

    ie he fill a surname so i need to fill name and adress too, but if he leave it blank i dont need to fill those 3 fields, thank you

  • Anyone have an example of getting this to work with the jQuery form plugin? I need to post my form via Ajax but am having issues.

    Thanks!

  • [...] A jQuery inline form validation, because validation is a mess Të Position Absolute 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. [...]

  • Is it possible to cancel the submit of a form if it doesn’t validate? I call specific functions on submit of different forms from the onsubmit attribute of the form. But this gets called regardless of whether the validation fails or not.

  • Ignore my last post. I found the success, and failure items in the js file. However the success function never appears to get triggered. The failure works fine.

    I changed it to success: function() { callSuccessFunction() },
    And added a corresponding function, but it never runs.

  • [...] A jQuery inline form validation, because validation is a mess Të Position AbsoluteWhen 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. [...]

  • [...] A jQuery inline form validation, because validation is a mess Të Position AbsoluteWhen 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. [...]

  • I have a checkbox on my form that hides some form elements, and makes the not required if clicked. The problem is, the error prompts still appear, and the form kind of moves up, making the error prompts appear in the incorrect place. How can I re-draw the active error prompts after I run $.validationEngine.closePrompt(‘.formError’, true);?

  • [...] I will create demos and document more these new features soon, I just had not time lately, but they are already up to grab in the project page. [...]

  • [...] A jQuery inline form validation, because validation is a mess Të Position Absolute 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. [...]

  • [...] DEMO Published in: [...]

  • [...] A jQuery inline form validation, because validation is a mess Të Position Absolute 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. [...]

  • Bonjour Cedric,

    Je me permet de te parler français au vu de ton message précédent :D un peu de la langue de Molière dans ce monde d’anglophone ne peut pas faire de mal.

    J’effectue actuellement ma validation lors de la soumission du formulaire. Les messages d’erreurs apparaissent correctement, cependant je voulais savoir si il était possible de faire disparaître le message d’erreur une fois que le champ a été sélectionné (Au moment ou il gagne le focus). En effet mon formulaire comporte de nombreux champs et les messages d’erreurs se superposent et masquent certains inputs, ce qui est assez gênant.

    Cordialement !

  • [...] A jQuery inline form validation, because validation is a mess Të Position Absolute 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. [...]

  • [...] 33.一个jQuery联表单验证 [...]

  • [...] A jQuery Inline Form Validation, because Validation is a Mess [...]

  • [...] A jQuery inline form validation, because validation is a mess Të Position Absolute 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. [...]

  • Is it possible to add something like length[9], so that it requires exactly 9 characters.
    I know I can use length[9,9], but then it says ‘Between 9 and 9 characters allowed’, which is a bit over informative :)

    Thanks for a great plugin!

  • Hi, Here a fix for umlaus (german)

    “onlyLetter”:{
    “regex”:”/^[a-zA-ZäüöÄÖÜß\ \']+$/”,
    “alertText”:”* Bitte nur Buchstaben”}

    Important: Save as UTF-8 Whitout BOM (its an option in WeBuilder2008)

  • I didn’t really take the time to read all the comments so this might have been mentioned already. Your regex for email validation is incorrect. I’m able to validate w/ no .tld example joe@joe works just fine. This should not be validated. Other than that great work, I really look forward to using this.

  • anyone know how to get it to submit to a mysql database? right now it doesn’t seem to be going anywhere

  • [...] A jQuery inline form validation, because validation is a mess Të Position Absolute 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. [...]

  • Hi,
    I have a problem getting valid HTML-Output with this Form-Validator. It is a great script, but some features are not working with other Programs because of the invalid code.

    In the “class” entry in each input-field there are brackets (“[" and "]“). These characters are not allowed in this filed.
    Maybe you could use something like “jqfv-required jqfv-custom-onlyLetter jqvf-length5-20″ instead of “validate[required, suctom[onlyLetter], length[5-20]]”…

    The brackets are allowed in the “name” attribute of an input-field but the script doesn’t close the messages any more if you use them there.

    Is there any way to get valid code without loosing updateability?

  • There is a problem with the script. On the first time a field triggers the onblur, it should validate the field, but it doesn’t. The second time the blur trigger’s the validation occurs. This can be done on the sample page. Just go directly to the ‘Date : (format YYYY-MM-DD)’ field, clear it and get out. It will not validate. Go into it again, get out and it will validate.

  • This seems to fix it:
    line 91:
    change:
    if($.validationEngine.intercept == false){

    to:
    if($.validationEngine.intercept == false || !$.validationEngine.intercept){

  • I’m also using Ajax, tiying to use the succss and failure functions. However, I also am finding that the success function never gets called, just the failure one. How can I discern if there is an error? Why isn’t the success function getting called? I don’t see a reply to the other post on this topic.

  • @fabio, I thnk you are right, somehow I erased the intercept declaration, I will patch it today, I will look into the sucfess function later today too

  • I fixed it — the problem was I had put “optional” as second parameter instead of first for my phonenumber field. I changed to:

    and now its happy!

  • The js has been patch, thank you again fabio,

    As for the success function, I just tested it, and it seems to work, I would need you to provide me the code or more explications, also don’t forget to abd the ”,’ like : function() { callSuccessFunction() },

  • Ah, I m happy it works for you Alan ;)

  • @Michael, yea I tought of that, I was using the anme attribut before but had problem with frameworks, I might look into a valid xhtml way later, it is not in the plans for now.

  • [...] A jQuery inline form val­i­da­tion, because val­i­da­tion is a mess Të Posi­tion AbsoluteWhen it comes to form val­i­da­tion, it’s hard to have a ver­sa­tile solu­tion that works with every form. Fig­ur­ing out how to dis­play errors is not a sim­ple task. This is some­thing I tried to rem­edy with this script. When an error needs to be dis­played, the script cre­ates a div and posi­tions it in the top right cor­ner of the input. This way you don’t have to worry about your HTML form struc­ture. The rounded cor­ner and shadow are done with CSS3 and degrade well in non com­pli­ant browsers. There is no images needed. [...]

  • Looks like there seems to be a bug…

    i have a huge form split into to small ones with divs like

    (div)(form id=”validate”)(/div)(div)…(/div)(div)(/form)(/div)

    only the inputs in the same div as the form-tag are validated.

  • [...] A jQuery inline form validation, because validation is a mess Të Position Absolute 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. [...]

  • can anyone help me i am using this validation and it works great but when I use ajaxUser I am experiencing “missing ) in parenthetical” please help me thnx..

    my code is

    “ajaxEmail”:{
    “file”:”http://192.168.1.158/newrespall/index.php/signup/autenticate_email”,
    “alertTextOk”:”* This user is available”,
    “alertTextLoad”:”* Loading, please wait”},
    “alertText”:”* This user is already taken”,

    file is in codeigniter framework the autenticate_email select the email if exist and echo
    This Email Address is already taken and This Email Address is available

    im getting missing ) in parenthetical error please help me thanks

  • Nice class. Thank you.

    One issue I’m having is creating a custom zip code class.

    “zipcode”:{
    “regex”:’/^\d{5}([\-]\d{4})?$/’,
    “alertText”:”Please enter valid Zip Code”},

    I’m getting the AlertText regardless. Thx.

RSSSome Tweets