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

Validations range from email, phone, url to more complex calls such as ajax processing.
Bundled in several locales, the error prompts can be translated in the locale of your choice.

**Important**: v2 is a significant rewrite of the original 1.7 branch. Please read the documentation as the API has changed! Also the documentation is always more up to date on the github README

Legacy 1.7 documentation and download can be found under package when you hit download on github

Installation

1. Unpack the archive
2. Include the script jquery.validationEngine.closure.js in your page
3. Pick the locale of the choice, include it in your page: jquery.validationEngine-XX.js
4. **Read this manual** and understand the API

Running the Demos

Most demos are functional by opening their respective HTML file. However, the Ajax demos require the use of Java6 to launch a lightweight http server.

1. Run the script `runDemo.bat` (Windows) or `runDemo.sh` (Unix) from the folder
2. Open a browser pointing at [http://localhost:9173](http://localhost:9173)

References

First link jQuery to the page

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js" type="text/javascript"></script>

Attach *jquery.validationEngine* and its locale

    <script src="js/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>

Finally link the desired theme

    <link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css"/>

Field validations

Validations are defined using the field’s **class** attribute. Here are a few examples showing how it happens:

    <input value="someone@nowhere.com" class="validate[required,custom[email]]" type="text" name="email" id="email" />
    <input value="2010-12-01" class="validate[required,custom[date]]" type="text" name="date" id="date" />
    <input value="too many spaces obviously" class="validate[required,custom[onlyLetterNumber]]" type="text" name="special" id="special" />

For more details about validators, please refer to the section below.

Instantiation

The validator is typically instantiated by using a call of the following form:

    $("#form.id").validationEngine(action or options);

The method takes one or several optional parameters, either an action (and parameters) or a list of options to customize the behavior of the engine.

Here comes a glimpse: say you have a form is this kind

    <form id="formID" method="post" action="submit.action">
        <input value="2010-12-01" class="validate[required,custom[date]]" type="text" name="date" id="date" />
    </form>

The following code would instance the validation engine:

    <script>
    $(document).ready(function(){
        $("#formID").validationEngine('attach');
       });
    </script>

Actions

init

Initializes the engine with default settings

    $("#formID1").validationEngine({promptPosition : "centerRight", scroll: false});
    $("#formID1").validationEngine('init', {promptPosition : "centerRight", scroll: false});
<pre>
 
<h3>attach</h3>
 
Attaches jQuery.validationEngine to form.submit and field.blur events.
<pre lang="html">
    $("#formID1").validationEngine('attach');
<pre/>
 
<h3>detach</h3>
 
Unregisters any bindings that may point to jQuery.validaitonEngine.
<pre lang="html">
    $("#formID1").validationEngine('detach');

validate

Validates the form and displays prompts accordingly. Returns *true* if the form validates, *false* if it contains errors. Note that if you use an ajax form validator, the actual result will be delivered asynchronously to the function *options.onAjaxFormComplete*.

    alert( $("#formID1").validationEngine('validate') );

showPrompt (promptText, type, promptPosition, showArrow)

Displays a prompt on a given element. Note that the prompt can be displayed on any element an id.

The method takes four parameters:
1. the text of the prompt itself
2. a type which defines the visual look of the prompt: ‘pass’ (green), ‘load’ (black) anything else (red)
3. an optional position: either “topLeft”, “topRight”, “bottomLeft”, “centerRight”, “bottomRight”. Defaults to *”topRight”*
4. an optional boolean which tells if the prompt should display a directional arrow

    <fieldset>
       <legend id="legendid">Email</legend>
       <a href="#" onclick="$('#legendid').validationEngine('showPrompt', 'This a custom msg', 'load')">Show prompt</a>
    </fieldset>

hide

Closes error prompts in the current form (in case you have more than one form on the page)

    $('#formID1').validationEngine('hide')">Hide prompts

hideAll

Closes **all** error prompts on the page.

    $('#formID1').validationEngine('hideAll');

Options

Options are typically passed to the init action as a parameter.
$(“#formID1”).validationEngine({promptPosition : “centerRight”, scroll: false});

validationEventTrigger

Name of the event triggering field validation, defaults to *blur*.

scroll
Tells if we should scroll the page to the first error, defaults to *true*.

promptPosition

Where should the prompt show ? Possible values are “topLeft”, “topRight”, “bottomLeft”, “centerRight”, “bottomRight”. Defaults to *”topRight”*.

ajaxFormValidation
If set to true, turns Ajax form validation logic on. defaults to *false*.
form validation takes place when the validate() action is called or when the form is submitted.

onBeforeAjaxFormValidation(form, options)
When ajaxFormValidation is turned on, function called before the asynchronous AJAX form validation call. May return false to stop the Ajax form validation

onAjaxFormComplete: function(form, status, errors, options)
When ajaxFormValidation is turned on, function is used to asynchronously process the result of the validation.

isOverflown
Set to true when the form shows in a scrolling div, defaults to *false*.

overflownDIV
Selector used to pick the overflown container, defaults to *””*.

Validators

Validators are encoded in the field’s class attribute, as such

required

Speaks by itself, fails if the element has no value. this validator can apply to pretty much any kind of input field.

    <input value="" class="validate[required]" type="text" name="email" id="email" />
    <input class="validate[required]" type="checkbox" id="agree" name="agree"/>
    <select name="sport" id="sport" class="validate[required]" id="sport">
       <option value="">Choose a sport</option>
       <option value="option1">Tennis</option>
       <option value="option2">Football</option>
       <option value="option3">Golf</option>
    </select>

custom[regex_name]

Validates the element’s value to a predefined list of regular expressions.

<input value="someone@nowhere.com" class="validate[required,custom[email]]" type="text" name="email" id="email" />

Please refer to the section Custom Regex for a list of available regular expressions.

function[methodName]

Validates a field using a third party function call. If a validation error occurs, the function must return an error message that will automatically show in the error prompt.

    function checkHELLO(field, rules, i, options){
      if (field.val() != "HELLO") {
         // this allows the use of i18 for the error msgs
         return options.allrules.validate2fields.alertText;
      }
    }

The following declaration will do

<input value="" class="validate[required,funcCall[checkHELLO]]" type="text" id="lastname" name="lastname" />

ajax[selector]

Delegates the validation to a server URL using an asynchronous Ajax request. The selector is used to identify a block of properties in the translation file, take the following example.

    <input value="" class="validate[required,custom[onlyLetterNumber],maxSize[20],ajax[ajaxUserCall]] text-input" type="text" name="user" id="user" />
 
 
 
    "ajaxUserCall": {
        "url": "ajaxValidateFieldUser",
        "extraData": "name=eric",
        "alertText": "* This user is already taken",
        "alertTextOk": "All good!",
        "alertTextLoad": "* Validating, please wait"
    },

* url – is the remote restful service to call
* extraData – optional parameters to sent
* alertText – error prompt message is validation fails
* alertTextOk – optional prompt is validation succeeds (shows green)
* alertTextLoad – message displayed while the validation is being performed

This validator is explained in further details in the Ajax section.

equals[field.id]
Check if the current field’s value equals the value of the specified field.

min[float]
Validates when the field’s value if less or equal to the given parameter.

max[float]
Validates when the field’s value if more or equal to the given parameter.

minSize[integer]
Validates if the element content size (in characters) is more or equal to the given *integer*. integer <= input.value.length maxSize[integer]
Validates if the element content size (in characters) is less or equal to the given *integer*. input.value.length <= integer past[NOW or a date]

Checks if the element’s value (which is implicitly a date) is earlier than the given *date*. When “NOW” is used as a parameter, the date will be calculate in the browser. Note that this may be different that the server date. Dates use the ISO format YYYY-MM-DD

    <input value="" class="validate[required,custom[date],past[now]]" type="text" id="birthdate" name="birthdate" />
    <input value="" class="validate[required,custom[date],past[2010-01-01]]" type="text" id="appointment" name="appointment" />

future[NOW or a date]

Checks if the element’s value (which is implicitly a date) is greater than the given *date*. When “NOW” is used as a parameter, the date will be calculate in the browser. Note that this may be different that the server date. Dates use the ISO format YYYY-MM-DD

    <input value="" class="validate[required,custom[date],future[now]]" type="text" id="appointment" name="appointment" /> // a date in 2009
    <input value="" class="validate[required,custom[date],future[2009-01-01],past[2009-12-31]]" type="text" id="d1" name="d1" />

minCheckbox[integer]

Validates when a minimum of *integer* checkboxes are selected.
The validator uses a special naming convention to identify the checkboxes part of the group.

The following example, enforces a minimum of two selected checkboxes

    <input class="validate[minCheckbox[2]]" type="checkbox" name="group1" id="maxcheck1" value="5"/>
    <input class="validate[minCheckbox[2]]" type="checkbox" name="group1" id="maxcheck2" value="3"/>
    <input class="validate[minCheckbox[2]]" type="checkbox" name="group1" id="maxcheck3" value="9"/>

Note how the input.name is identical across the fields.

maxCheckbox[integer]

Same as above but limits the maximum number of selected check boxes.

Selectors

We’ve introduced the notion of selectors without giving much details about them: A selector is a string which is used as a key to match properties in the translation files.
Take the following example:

    "onlyNumber": {
        "regex": /^[0-9\ ]+$/,
        "alertText": "* Numbers only"
    },
    "ajaxUserCall": {
        "url": "ajaxValidateFieldUser",
        "extraData": "name=eric",
        "alertText": "* This user is already taken",
        "alertTextLoad": "* Validating, please wait"
    },
    "validate2fields": {
        "alertText": "* Please input HELLO"
    }

onlyNumber, onlyLetter and validate2fields are all selectors. jQuery.validationEngine comes with a standard set but you are welcome to add you own to define AJAX backend services, error messages and/or new regular expressions.

Ajax

Ajax validation comes in two flavors:

1. Field Ajax validations, which takes place when the user inputs a value in a field and moves away.
2. Form Ajax validation, which takes place when the form is submitted or when the validate() action is called.

Both options are optional.

Protocol

The client sends the form fields and values as a GET request to the form.action url.

Client calls url?fieldId=id1&fieldValue=value1&…etc ==> Server (form.action)

Server responds with a list of arrays: [fieldid, status, errorMsg].

* fieldid is the name (id) of the field
* status is the result of the validation, true if it passes, false if it fails
* errorMsg is an error string (or a selector) to the prompt text

Client receives <== [["id1", boolean,"errorMsg"],["id2", false, "there is an error "],["id3", true, "this field is good"]] Server Note that only errors (status=false) shall be returned from the server. However you may also decide to return an entry with a status=true in which case the errorMsg will show as a green prompt.

Callbacks

Since the form validation is asynchronously delegated to the form action, we provide two callback methods:

**onBeforeAjaxFormValidation(form, options)** is called before the ajax form validation call, it may return false to stop the request

**onAjaxFormComplete: function(form, status, json_response_from_server, options)** is called after the ajax form validation call

Custom Regex

jQuery.validationEngine comes with a lot of predefined expressions. Regex are specified as such:

<input value="" class="validate[custom[email]]" type="text" name="email" id="email" />

Note that the selector identifies a given regular expression in the translation file, but also its associated error prompt messages and optional green prompt message.

phone
a typical phone number with an optional country code and extension. Note that the validation is **relaxed**, please add extra validations for your specific country.

49-4312 / 777 777
+1 (305) 613-0958 x101
(305) 613 09 58 ext 101
3056130958
+33 1 47 37 62 24 extension 3
(016977) 1234
04312 – 777 777
91-12345-12345
+58 295416 7216

url
matched a url such as http://myserver.com, https://www.crionics.com or ftp://myserver.ws

email
easy, an email : username@hostname.com

date
an ISO date, YYYY-MM-DD

number
floating points with an optional sign. ie. -143.22 or .77 but also +234,23

integer
integers with an optional sign. ie. -635 +2201 738

ipv4
an IP address (v4) ie. 127.0.0.1

onlyNumberSp
Only numbers and spaces characters

onlyLetterSp
Only letters and space characters

onlyLetterNumber
Only letters and numbers, no space

Using the engine in a overflown div

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.

Customizations

What would be a good library without customization ?

Adding regular expressions

Adding new regular expressions is easy: open your translation file and add a new entry to the list

    "onlyLetter": {
        "regex": /^[a-zA-Z\ \']+$/,
        "alertText": "* Letters only"
    },

* “onlyLetter” is a sample selector name
* “regex” is a javascript regular expression
* “alertText” is the message to display when the validation fails

You can now use the new regular expression as such

<input type="text" id="myid" name="myid" class="validation[custom[onlyLetter]]"/>

Don’t forget to contribute!

Customizing the look and feel

Edit the file *validationEngine.jquery.css* and customize the stylesheet to your likings. it’s trivial if you know CSS.

Adding more locales

You can easy add a locale by taking *jquery.validationEngine-en.js* as an example.
Feel free to share the translation 😉

Rules of thumb

* field.id are **unique** across the page
* for simplicity and consistency field.id and field.name should match (except with minCheckbox and maxCheckbox validators)
* spaces or special chars should be avoided in field.id or field.name
* use lower cases for input.type ie. *text, password, textarea, checkbox, radio*
* use the Ajax validator last ie. validate[custom[onlyLetter],length[0,100],**ajax[ajaxNameCall]**]
* use only one Ajax validator per field!
* JSON services should live on the same server (or you will get into browser security issues)
* in a perfect RESTful world, http **GET** is used to *READ* data, http **POST** is used to *WRITE* data: which translates into -> Ajax validations should use GET, the actual form post should use a POST request.

Contribution

Contributions are always welcome, you may refer to the latest stable project at [GitHub](https://github.com/posabsolute/jQuery-Validation-Engine)
We use [Aptana](http://www.aptana.com/) as a Javascript editor and the Rockstart JSLint & Closure plugins http://update.rockstarapps.com/site.xml

License

Licensed under the MIT License

Authors

Copyright(c) 2010 Cedric Dugas
v2.0 Rewrite by Olivier Refalo


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.1 Online
October 20 2010, release v1.7.1: Compatibility release for jQUery 1.4.3
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.

Ads

Become expert in web development with testking using self paced testking HP0-D07 study guides and testking 646-671 jQuery tutorials.

491 thoughts on “A jQuery inline form validation, because validation is a mess

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

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

  3. 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!

  4. 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.

  5. 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.

  6. Je suppose que tu parle français donc je le dit en FR 😀

    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 !

  7. 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.

  8. 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

  9. 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!

  10. 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.

  11. 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.

  12. 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);?

  13. Bonjour Cedric,

    Je me permet de te parler français au vu de ton message précédent 😀 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 !

  14. 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!

  15. 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)

  16. 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.

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

  18. 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?

  19. 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.

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

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

  21. 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.

  22. @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

  23. 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!

  24. 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() },

  25. @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.

  26. 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.

  27. 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

  28. 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.

  29. Upgraded to the new version, but none of the validations work now. I tried #.validationEngine.loadValidation(“#elem”) and it says TypeError: $.validationEngine.settings is undefined.

    Browser: FF3.5

Comments are closed.