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!









I love your code… definitely one of the nicest form validation bits for the client side out there. My only request would be something to enable multiple forms on the same page. For example, I’m currently giving this a test drive on my login/registration page for the registration fields but triggers when the user clicks the button to login OR register.
Again, thank you for a great piece of code and all the work that went into it.
Hello Again!
I made another modification, because the default behavior wasn’t working for my application. Basically, I have a form with a mix of required and optional fields, all of them have this validation plug-in applied. When I would tab out of a non-required field that I left blank, the warning box would still pop up, telling me all the “rules”. This isn’t neccessary, as I only want to warn the user (for a non-required field), *if* they enter a value that doesn’t meet the required validation.
So, I modded the JS to only show the waring box if (required == true or (required == false and field is not blank)).
I can provide mods if desired.
Thanks again for all your hard work on this beautiful plug-in!
Ryan King
Synesis, Inc.
http://www.GoSynesis.com
[...] http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/ [...]
Hey,
thx for date and dropdown validation implementation. Great Stuff.
One last Question: If i choose validation onlyLetter in a textfield, there is no way to type a space between 2 words. What is the regex for a space….
PS. Sorry for my bad english, i am from germany.
Hello,
i got it:
“onlyLetter”:{
“regex”:”/^([a-zA-ZwäöüÄÖÜß,-]|\\s)+$/”,
v1.2 online, space has been added in regEx and a corrected an error with multiple form on the same page
@rjking I added optional validation, thank you for the idea, I did not code it the same way you did, however yours is just as good.
Can i do server side validation through this ? Like email address already exist or not
@Shariq, no, I guess you could modify it, but it does not listen to Ajax response.
Hey there, I think I found something kind of like a bug.
On my test site I was playing around with this AWESOME script and I was testing out the email regex. Looks pretty solid actually (if you ask me), but when I was stress testing it with the following test string:
jpop@jpop.jpop.jpop.jpop.jpop.jpop.jpop.jpop.jpop.jpop.jpop.jpop.jpop.jpop.jpop.jpop
it went into a crazy loop and froze up my browser. Firefox says it’s line 227 – right around the regex handling stuff. Not a big deal as I doubt anyone will ever enter an email that long (Technically, they can’t be longer than 320 chars anyway), but thought you might want to try this out for yourself.
@capnjeremy yeah well this is a standard regex, but I can see how the browser crashed from your pattern
@Cedric: A request, can you provide option for checkbox array?
hi, what I have to change if I have to use :
”
Validate & Send the form!
”
instead of:
“”
Can someone help me please?
Hi, what I have to change if I use a “a href” button instead of normal button with type=”submit”?
how can i get it to check if two fields are filled out before it runs the validation?
I guess you could add your code before I do my validation in the form submit on line 68
im not that good at jquery, what would i write?
what i have is a form that has the first and last name in the same row, and the 3 separated phone number fields. i currently am trying to write something on line 18 that checks both field one and field two.
What should I do to pass my form into database using ajax.
I’ve been following your tutorial and add some code like below but it still no data in the database.
function callSuccessFunction(){
$(“form#submit”).submit(function(){
$.ajax({
type: “POST”,
url: “ajax.php”,
data: $(‘form#submit’).serialize(),
success :function(){
$(‘form#submit’).hide();
$(‘div.success’).fadeIn();}
});
return false;
});
}
this is not the right place, you need to follow my instruction in the ajax section
replace “success: false,” by: success : function() { callSuccessFunction() }, and
the right place is in the callSuccessFunction() on the index.html (this function could be anywhere)
Hi, I’m having trouble making an url custom regex, it seems to have some trouble with “/” symbols, so /^(https?\/\/)/ crews up, and none of those I found on the internets worked. Mind that I’m a bit rusty on the regex part.
Back with a solution: /^(https?:\\x2F\\x2F)?((\w){3}.)?/ and the rest is up to you.
I’m not a brilliant regex coder, what are your trying to do?
[...] jQuery inline form validation [...]
Cedric,
I think I have found a slight bug in the demo. In “Favorite Sport 2″, if I select “Choose a sport”, it doesn’t give me a validation tooltip.
Cheers.
Is it possible to extend the JQuery validation plugin from ba.assistance.de with your error message display since it seems a more mature validation plugin, but your display is excellent
thank you for the reply, but…I’ve actually done that. replace “success: false” and then writing the code i’ve write b4 in my index.html
It does the ajax b’cause the form can hide and the div.success displayed. I think the one that doesn’t work is the serialize() command. Can you give me a sort example on how should I write the ajax code to pass my form into my database…?
thanks a lot…
@Stephen, I suppose someone could port it, my code is on mit licence so if anyone want to port it, fair enough
@christopher, seems like a bug, will have a look this week.
@stev you could try to send every input value, but serialize should work, try to send 1 input $(input#id).val() in data , and check if your php receive it. Install firebug to see what is posted, give me your email, I can send you someting you can work with tommorrow
thanks a lot….
I’ll try it.
here is my e-mail : stevanni@elect-eng.its.ac.id
Prompts aren’t disappearing after entering fulfilling validation requirements. I’ve got a lot of javascript on this site so maybe a conflict of some sort, but I’m not able to pull any errors out of firebug. If someone had a minute to take a peak I’d appreciate it. Its a really slick validation code by the way. (sibu beauty free trial . com)
I have some URLs like this:
http://radioizvor.org/mySite/ or http://www.radioizvor.org/mySite/
and
http://students.info.uaic.ro/~mpotoceanu/mySite2/
I want to create a rule for web url.
My curent rule is this:
“regex”: “/^((\w){3}\.)([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/”,
this rule validate for moment only URL like http://www.somethig.uk
Someone have a solution for more complex URL like those above?
facing and issur while using .net textboxes the error msg does not fade out even after entering the correct data.. where as when i replace the asp:textbox with html input boxes it works fine….
your .net textboxes give what kind of html form field, textarea? what rules did you use
@8asic the problem is that I use the name attribute too, this is something I will need to change in a near future
For all Germans using UTF-8 you have to modify the “only letters” regex like this:
“onlyLetter”:{
“regex”:”/^([a-zA-ZäüöÄÜÖß\ \']|\\s)+$/”,
“alertText”:”* Nur Buchstaben erlaubt”}
This is one great plugin, thanx for al your hard work man!
I do have a problem with implementing it though. If you add the validation to a form inside a scrollable div (overflow), the coordinates of the ballons get messed up when you scroll. Turning the overflow of immediately fixes the issue. Point is, I have a long form inside a thickbox iframe popup (limited screen real-estate) and thus need the overflow in order to keep the buttons visible at all time.
Any tips?
How to make the message box larger ? I want to set the width to a higher value, and I don’t find where to modify the code.
I found these lines in js/validationEngine.js
callerWidth = $(caller).width()
callerHeight = $(caller).height()
inputHeight = $(divFormError).height()
callerleftPosition = callerleftPosition + callerWidth -30
callerTopPosition = callerTopPosition -inputHeight -10
but here is the positioning of the message box on the screen, not the width of the message.
Little bug for you: the validation doesn’t count Umlauts (äüöÄÖÜß) as letters. Very bad for international usage …
[...] Click here to view [...]
beautifull validation!!!
I am a designer/photographer… so I suck when it comes to jquery etc. I am trying to call the mail.php but I want to stay on the same page. I set the form to display none and display a message but I dont know how to continue and call the mail.php and stay on the same page.
$(“[class^=validate]“).validationEngine({
success : function() { $(‘#form’).hide(); $(‘p.test’).text(‘thank you’) () },,
failure : function() { callFailFunction() }
})
I would really appreciate it if someone can help me with this.
Noel
Amsterdam
@Cedric Dugas
When trying to use this in .Net as .Net programmer says, the box does not fade out after you put something into the box and it loses focus. This is how my e-mail textbox is rendered to HTML:
Any help is much appreciated and as has been mentioned this is the best visual implementation for client-side validation I have seen! keep up the good work!!
the code didn’t come up so I’m trying to add a _ to the beginning and end..
Nope didn’t work.. last try:
IMPUT name=”ctl10$txtEmail” type=”text” id=”ctl10_txtEmail” tabindex=”13″ class=”validate[required,custom[email]] text-input” |>>>>
[...] jQuery validation engine, yet another nice form validation plugin for jquery javascript framework, comes with language localization supported and many predefined validation rules: [...]
@Markive : As I said before I use the attribute name, unfortunately the .net framework like to temper with this attribut too. This is something I’m trying to change for v1.3
[...] form. Figuring out how to arrangement errors is not a elementary task. Cedric Dugas has combined a jQuery Validation Engine in sequence to compromise this [...]
[...] A jQuery inline form validation, because validation is a mess « Position Absolute (tags: jquery forms validation) [...]
Looks pretty good. You should get this up on github so the community can help with hit. Thanks
hello cedric, I”ve tried to do send one input using val() to get the data and send it using $.ajax

But, just like before…no data send to my database. Still waiting for your code in my mailbox.
thanks…
PS: Sorry for not replying again in here, coz i’m really out of internet zone. :p
Great validation script. One question. Is there a way to like reset the form i.e. close all the bubbles with one click of a button or hyperlink?