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”

  • Look at your documen ready, you now have to validate to your form instead of directly to you class

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

  • [...] script, please consider buying me a beer, it’s cheap and a simple way to give back! source :: position-absolute Share and [...]

  • Hi. Very good thing you did. But some bad things is there i think.

    I will try to redo your function in future, if you will not to do this.

    1) What if user want to exclude some bad words from sending.
    Your thing should have way to execute some custom rule in not reg ex, but something like this if(jQuery(“#field”).val()==’bad expression’) { eror =1; }

    2) i think is bad that all error shows at one time. I think it should breaks if one erorr cathed.. like in queue.

    My input have text inside this so i should check is standart value is inside or user’s text … and don’t know how to do this.

    If something will be cahnged in your script, please email me. rantie86@gmail.com

    But this very cool thing.

  • Hello there , again :D

    I have found some minor problem, if the input is fixed near the top side on the page when the error message appear it is partly hidden. I tried to change the callerTopPosition by
    “callerTopPosition = callerTopPosition – (callerHeight/2) -10″ it fits perflecty. But when you display another message it return to his previous location or if the message is too long it appear under the input :s
    i do not know what to do :’(

  • Hey Lifty,

    You need to change the update function too, I really never encounter a website where I had to do this, I guess I could write a condition for it in the ”near’ future

  • how do we do a MIN checkbox?

    you even called it:

    minCheckbox[7]

  • Yea I guess I inversed this, it is not implemented right now sorry.

  • [...] Motor de validação de formulários jQuery foi testado com sucesso em Internet Explorer 6 & 7, Firefox 3+, Safari 4 e Chrome [...]

  • Does it work with file-boxes? I get “Filename cannot be empty ” when sending the form.

  • Using ajaxSubmit that is.

  • how can i make radio button be a required field co’z when I use validate required, the form still submits. tnx,

  • it validate it first, but when I submit again.. the validation does not work please post the solution tnx..

  • Hi there. Thanks for the nice validation plugin. However, I’ve been trying to get this simple regex to work to no avail for hours now. Any help perhaps please? Here is the custom regex I’m trying to use: “regex”:”/^(?=.*\d)(?=.*[A-Z]).{8,20}$/”

  • hi Cedric,
    firstavail, thank you for this plugin, very nice job!
    I’m trying to use the language file (jquery.validationEngine-fr.js), including it just before jquery.validationEngine.js , but it doesn’t work. Here is the error in firebug:
    “$.validationEngine.settings.allrules is undefined”.
    I’m using jquery 1.3.2
    What am I doing wrong?
    cheers

  • @osdave, it should work right out of the box, I will have a look this afternoon

  • thx for your support, Cedric.
    I’ll be waiting for your comments. Meanwhile I keep looking.
    By the way, I’m working with Zend Framework, if that matters.

  • Salut excuse moi j’ai un problème tout mon jquery est bien lancé et le css aussi = executé mais je n’ai pas de message d’erreur qui s’affiche :(

  • @osdave, ok just check my download version, if I uncomment the french js file its work, now, if you added rules, please make sure you followed the good structure. Its kind of hard to know the problem without seeing the code

    @shinzo as tu vien mis le valide[] en permier dans ton attrivut class? c<est deja arriver à quelqu’un d’autre aussi et c’étais le probleme

  • well, i found my problem: ZF is working LIFO (Last In First Out), that means that I need to write first what needs to be called last.
    For example, for what I’m doing right now, here is what’s in the beginning of my view:
    headLink()->appendStylesheet($this->baseUrl() . ‘/public/css/validationEngine.jquery.css’);
    $this->headScript()->appendFile($this->baseUrl() . ‘/public/js/jquery/jquery.validationEngine.js’);
    $this->headScript()->appendFile($this->baseUrl() . ‘/public/js/jquery/jquery.validationEngine-es.js’);
    $this->headScript()->appendFile($this->baseUrl() . ‘/public/js/forms/registrar.js’);
    ?>

    Sorry for wasting your time, Cedric, and thanks again for your support.
    see you

  • @osdave, well this will be useful, we use zend at work too ;)

  • Hi, i think this is a cool jquery plugin. Wondering how to hide the submit button upon submission once all the fields pass the checking. I manage to hide the submit button but the form is not submitted. I add the function to hide the submit button in the success property. Any idea?

  • Bonjour merci de ta réponse oui j’obtiens ça ^^

    Car je le met avec elgg et j’obtiens bien

  • A mon code a pas été mis désolé

    sans les ‘ évidement

  • class=”validate[custom[onlyLetter],required]” value=”01″

  • j ai remarquer une chose quand je clique sur un autre form et en mettant le mauvais contenue, mon element . styl me marque top: -1643px donc j ai tout a -1643 oO

    et quand je marque le bon contenue sa me recharge ma page et pouf sa merde…

  • Is there a variable corresponding to number of errors in the form?

  • @schturdark well the success fonction stop the submit , there is no call back this way, but I will be implimenting one shortly, for now you can go in the scress where teh success function is called and add you callback juste before the return false

    @Ahmet no it’s not implimented,

    @shinzo lance tu mon script dans un iframe?

  • Non du tout

    En fait j’ai un plugin qui va transformer creer ma class suivant les element typ)text ou type=checkbox…..

    Après je crèe un formulaire = autre plugin ou je met la fonction $document.ready.

    Et là tout merdouille mon css et JS bien chargé mais bon je comprend pas pourquoi sa me fait ça. Surtout que là ouvel erreur => uncaught exception: Syntax error, unrecognized expression: .
    il reconnais pas le . oO

  • What can I say except the thing that others already said. Brilliant plugin, brilliant work.
    And I have some tricky problem.
    This plugin works as expected in IE but not in Mozilla.
    Both browsers show baloons when some fields loose focus and here is the difference. When I click submit button IE doesnt do that if the rules arent met. However, Mozilla show ballons quickly and then submit no matter what.

    Here is the piece of my code:

    $(document).ready(function() {

    // SUCCESS AJAX CALL, replace “success: false,” by: success : function() { callSuccessFunction() },
    $(“[class^=validate]“).validationEngine({
    success : function() { Posalji_formu() },
    failure : function() { Neuspesno() }
    })
    });

    It is located on top of jquery.validationEngine.js file.
    In my asp page I have functions Posalji_formu and Neuspesno.

    function Posalji_formu()
    {
    frm = document.formID;
    frm.action=”page.asp?p=1&i=”;
    frm.submit();
    }

    Do You have any hint what could be a problem?
    Thanks in advance.

  • @Bosko, do you have any error that popup in the javascript console?

  • Error from console:

    Error: Posalji_formu is not defined
    Source File: http://www.pobratim.rs/nea/js/jquery.validationEngine.js
    Line: 15

  • Try using lowercase for the first letter of you function, it seems like this function do not exist, this function should be outside of my prototype and outside of document ready,

    Also, you should use my last version, I changed lots of thing and fixed some bugs.

    but it’s not working exactly the same, in the new version you call directly the form to validate in the dom.ready and every input need an ID

  • I had given the solution for the date-picker on 15th of june

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

  • Will inform You on results Cedric. Thanks.
    Can You please edit my previous post about error and replace the address with something generic. Cant find Your email here, I would send You this request by email.
    Thanks again.

  • [...] 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. [...]

  • Salut désolé de te redéranger. J’ai un soucis ^^

    Mon JS et CSS sont bien appelé mais j’ai cela : uncaught exception: Syntax error, unrecognized expression: .

    sur cette ligne
    $(“#cveuroform”).validationEngine({

    Aurais tu une idée?

    ps: La fonction existe bien

  • I finally found out what was the problem.
    My from is nested in table like this:

    When I put it like this:

    It works like a charm.
    Cedric, is there anything I can change in js file to be able to overcome this?
    Thanks in advance.

  • <table…>
    <form…>

    is not correct

    <form…>
    <table…>

    is correct one

  • Problème réglé il faut mettre un id dans le input du même nom que le name

  • I have another problem the correction does not disapear

  • Awesome awesome script :) Ok well this newer version screwed what I was doing :) Right now I have it so that there is no action in the form. If your validation works, and then I do a couple other validation routines, check image upload fields since it doesnt look like your script works with those, and then I do another test, then I assign the action attribute to the form and return true. It used to then submit the form, but now, its’ not submitting the form and Im not sure why.. any help would be appreciated.. by anyone! :)

  • @Rick Baskett:

    A piece of Your code would be useful. :)

  • @Bosko: thanks for your response.. looks like it might have rejected my last post with the script content. If you go here: http://www.mppumayri.org/security-form.htm

    View the source code, the important stuff is down at the bottom. If I remove the success callback then it works, but I really would like that code to fire on success of the validation routine.

  • Im working on it as I write this so the code is going to continue changing :)

  • Why is this line commented:

    //$(‘form’).submit();

    Did You try to use $(‘#form’) instead of $(‘form’)?

  • That’s commented out because it basically kept submitting the form, which then alerted me that the form should have submitted and then kept looping. It was ugly :)

    And yeah I tried #form, I made sure that $(‘form’) would work by setting the css(‘background-color’,'red’) and then also viewing the generated source code and it was definitely working. Whenever I have something besides succes: false, or success: function(){} it will fail, so there is something wrong with the success method.

  • And what about this line:

    var formAction = ’security-form.htm?action=submit’;

    The form is submitting to itself over and over once You fill all the fields and click submit button. Since You placed it in document.ready… this is the result.
    Did You try to submit Your data to some other page which would process form field values?

  • It’s actually not in document.ready. And yep I even removed the formAction and set it explicitly in the form tag and still no go. Seriously the problem is in the success method, it seems to always be returning false.

  • Do you know what is going on here?

    if($.validationEngine.submitValidation(this,settings) == false){
    if($.validationEngine.submitForm(this,settings) == true) {return false;}
    }

    $.validationEngine.submitForm(this,settings) == true always seems to evaluate to true, which then returns false…

RSSSome Tweets