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.
-
<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" charset="utf-8" />
-
<script src="js/jquery.js" type="text/javascript"></script>
-
<script src="js/jquery.validationEngine-en.js" type="text/javascript"></script>
-
<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.
-
$(document).ready(function() {
-
$("#formID").validationEngine()
-
})
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.
-
<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.
-
"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:
-
<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" charset="utf-8" />
-
<script src="js/jquery.js" type="text/javascript"></script>
-
<script src="js/jquery.validationEngine-fr.js" type="text/javascript"></script>
-
<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,
-
$("#formID").validationEngine({
-
inlineValidation: false,
-
success : false,
-
failure : function() { callFailFunction() }
-
})
Change validation event trigger
You can change the event that trigger the validation in the settings, default is blur
-
$("#formID").validationEngine({
-
validationEventTriggers:"keyup blur", //will validate on keyup and blur
-
success : false,
-
failure : function() { callFailFunction() }
-
})
No scrolling
-
$("#formID").validationEngine({scroll:false})
Validate and return true or false
Can be use anywhere in your script
-
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.
-
$("#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.
-
$("#formID").validationEngine({
-
promptPosition: "topRight", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight
-
success : false,
-
failure : function() {
-
})
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:
-
<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):
-
"validate2fields":{
-
"nname":"validate2fields",
-
"alertText":"* You must have a firstname and a lastname"}
-
}
Now the custom function that could be anywhere in your JS
-
function validate2fields(){
-
if($("#firstname").val() =="" || $("#lastname").val() == ""){
-
return true;
-
}else{
-
return false;
-
}
-
}
Validation in overflown div and lightbox with scrollable content
To get the supported mode you need to add these options when instancing your plugin:
-
$("#formID").validationEngine({
-
containerOverflow:true, // Enable Overflown mode
-
containerOverflowDOM:"#divOverflown" // The actual DOM element container with overflow scroll on it
-
})
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
-
$("#formID").validationEngine({
-
ajaxSubmit: true,
-
ajaxSubmitFile: "ajaxSubmit.php",
-
ajaxSubmitMessage: "Thank you, we received your inscription!",
-
ajaxSubmitExtraData: "securityCode=38709238423&name=john",
-
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() }
-
})
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”
Articles
Some Tweets
- kind of old, bit I like it http://www.thereisnopagefold.com/
- I really have a love/hate relationship with the E texteditor, so good but so bad at the same time
- onclick on a form instead of submit? Please never do javascript again
- Question: do you think the mobile web has a viable market right more? Pretty hard to convince clients to invest
- I meant jquery mobile.. meh
- Looks like sencha touch will have competition, jquery touch is looking hot!









If you can make this work with multiple validation groups…
Even the idea would be great
[...] A jQuery inline form validation, because validation is a mess « Position Absoluteposition-absolute.com [...]
Sorry, It works but the error boxes are not rounded corner
As said, rounded corner are done in css3, IE cannot see them
Your email validation is overly restrictive. Valid email adresses can contain + signs and other characters.
This often used when doing automatic filtering based on the +keyword part of the email in gmail.
ex. myname+keyword@gmail.com
@tom gonna look into it, however this is easy to personalized.
my server is experiencing issues, I think I nailed the problem, sorry for the downtime
Nice script
Hi Cedric, great work. Very slick and easy to customize.
how about internationalisation? ö is a correct letter in my language.
@ernesto internationalisation = localisation, you can localize to any language you like
It’s nice but what if I disable javascript ? Validation truly must be done on server side in order for it to work. Client side can only help.
@tony , This is not intended to replace a server side validation,
This is intended as a nice way to guide your users or if you are doing ajax applications
Love it! Well done. My one caveat is the use of the class attribute for this. A custom attribute I think would be better, say
That way you can avoid cluttering up the class attribute and actually it would give you more flexibility in the validation notation. I bet it could be reduced to something like:
@trans you cannot put code in comments sorry, the problem with custom attributes, is that the w3c will never validate them.
I understand the cluttering issue, but this is really an html validation choice I took. And I don’t say it is the right choice, it was the right choice for me.
nice work… but…
scroll fx is ugly on opera 9.64 :s
good job dude!
Really nice jquery plugin i was looking for it there is one for mootools but not for jquery
Nice Ced !
[...] jQuery Inline Form Validation [...]
Very well done. Thank you for your contribution to opensource world.
My only question is: could you re-work those nice blurred shadows for CSS 2.1? It is nice to have CSS 3 effects ready on hand, but I think it will take some time until they will be accepted widely.
@Serrirre well I could, but I really didn’t want to add 8 png, but it would not be to hard for you to add them in the css I think
Any chance of a minified version of the script? I tried running it through a minifier myself, but it no longer works…
[...] jQuery Plugin – A jQuery inline form validation, because validation is a mess (Suggested by jQuery) [...]
Nice form validation. Thanks for sharing.
One point – Internationalization is not the same as localization. Localization is the translation of strings, resizing of UI to accomodate different language versions of your product. Internationalization or globalization is the ability of your code to support multiple input/display characters to name but one area.
@shay, Thanks to point me that out, there is no internationalization planned currently
Very well done. Thank you for your contribution to opensource world.
But, i miss the validation of a dropdown box and the validation vor date (dd.mm.jjjj). Is there a way to include my wishes?
@Maschi, date validation should be up this weekend, I have problems with my server, and optimizing it take me too much time..
required select is on my list, but I cannot give a release date, should be not too far tho
For validation on select boxes…
Just add this after line 191:
if (callerType == “select-one”) { // added by paul@kinetek.net for select boxes
callerName = $(caller).attr(“name”);
if(!$(“select[name="+callerName+"]“).val()) {
isError = true;
promptText += settings.allrules[rules[i]].alertText+”";
}
}
Note: Your empty option in the select box must have the value attribute or this won’t work.
Example:
Select One
Also, you just need to add ; on the end of lines that don’t have them to minify it. Remember to do them after the closing } after functions and if statements. My file is just one line now and 6.2kb.
Btw, thanks for the great plugin Cedric. Best validation plugin i’ve seen so far.
Oops, I guess your stripping html so my example didn’t work…
Let’s try again
<option value=”">– Select One –</option>
Thx paul, I will add this.
Np. Glad I could contribute. I’m fairly new to jquery so that type (select-one) threw me off. I didn’t think it was correct but it looks like it is.
[...] http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/ [...]
How can I add required validation for dropdownlist and radio buttons?
thanks.
Arh sorry, please ignore the above. I just saw Paul’s code and it’s working now. thanks.
hi! i just want to ask how can I change the color of arrow? thank you guys.
oh sorry..i know now..hehee thank you for this!!!cheers!@
Bit intrusive, might be an idea to have an option to only show messages on error.
Also, when you have entered in a few fields and go back to edit one of the earlier fields, the message for the previously focused field still shows and the one for the newly focused field doesn’t.
@Anonymous Error messages are parsed on the blur event
Great plugin
but there is issue when using
” [ " " ] ”
characters in name attribute eg data[name] .
error tooltip wont disappear when using mentioned characters.
@Sajid, True you cannot use ‘ in the name input, I guess you could just put required, that was just an example of letters only.
@Cedric
what i meant was [ ] characters
which normally used to handle multiple selections etc
what i got from studying plugin code is you used NAME attribute as className for error tooltip and [ and ] characters wont work in fetching element via $(“.”) function of jquery
$(“.data [Member] [favs]“) wont return anything and whats why
$(“.”+closingPrompt).remove(); not removing tooltip.
although i did changed the plugin code to use input element’s ID as className for error Tooltip and it works
Thanks for the tip, I added normal select ad multiple select in the script, using id for the multiple select
Hello – Great Plugin!
I’m experiencing same issue as Cedric… I have field arrays in my form, so end up with, for example, >input name=”fname[]” … $gt; , which breaks jQuery calls… should I modify script to use IDs like Cedric, or do you expect to have an official released fix sometime in the near future?
Thanks agin!
rjking could you put your example online, I already corrected the behavior in the multiple select using ids,
But yeah ultimately I will have to change name by id, wich is sad because I will break the html compatibility with earlier versions.
Hi Cedric-
Yeah, not ideal to use IDs, but was required in my case. I made 12 edits to your code, and got it working. Now, I am still adding the validation rules to the class attribute of the element (like your original method), however for the new div that your JS creates, I switched to defining its class from the ID of the form element instead, so all I have to do is make sure there’s a unique ID on each element in my form (which of course isn’t a problem for validation). I didn’t necessarily have an ID assigned to all my form elements before, so this was the only modification I made to my code.
Here’s a sample input element from my form:
<input type=”text” id=”field_id_42″ name=”emp_array[6][fname][]” class=”validate[required,custom[onlyLetter],length[4,100]]” value=”James” />
Which now works with the modifications I made to your JS code (I can send you my modifications if it would help at all).
p.s. – I just realized I used your name, Cedric, in my original post…
I meant I was seeing the same thing as Sajid.
Anyways, one other minor note, possibly intentional on your part, but the “onlyLetter” and “noSpecialCharacters” don’t allow spaces. No biggie of course since using regex, but just thought I’d share. Couldn’t figure out for a few minutes why it didn’t like “John Smith” in a name field, with “onlyLetter” applied… kept telling me “Letters Only”… lol
Very good point… I will add space in the reg ex tomorrow…
Silly error…
another minor error… “noSpecialCharacters” is mis-spelled…
Man, the more I use this plug-in, the better it gets…. great work!
Ryan King
Synesis, Inc.
http://www.GoSynesis.com