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. Just few enhancements : the goal is to have a better look so I changed the div to a ul/li sequence in order to display the errors in a full css way.

    See it in action : http://kocoon.krisszone.com/contact.html

    in JS :
    change formErrorContent to ul instead of div
    ==> var formErrorContent = document.createElement(‘ul’);
    embrace all promptText definitions with
    like promptText += ”+settings.allrules[rules[i]].alertTextCheckboxe+””;

    Suppress all * in the errors label.

    in CSS : in the .formError .formErrorContent css settings, add the design of your chips.
    here I choosed : list-style-type:square;

    And hereafter a french implementation :

    “required”:{
    “regex”:”none”,
    “alertText”:”Ce champ est obligatoire.”,
    “alertTextCheckboxMultiple”:”Choisir une option.”,
    “alertTextCheckboxe”:”Ce choix est obligatoire.”},
    “length”:{
    “regex”:”none”,
    “alertText”:”Entre “,
    “alertText2″:” et “,
    “alertText3″:” caractères obligatoires.”},
    “minCheckbox”:{
    “regex”:”none”,
    “alertText”:”Le nombre maximum de choix est atteint.”},
    “confirm”:{
    “regex”:”none”,
    “alertText”:”Les champs ne sont pas identiques.”},
    “telephone”:{
    “regex”:”/^[0-9\-\(\)\ ]{10}$/”,
    “alertText”:”Numéro de téléphone invalide.”},
    “codePostal”:{
    “regex”:”/^[0-9\-\(\)\ ]{6}$/”,
    “alertText”:”Code postal invalide.”},
    “email”:{
    “regex”:”/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/”,
    “alertText”:”Courriel invalide.”},
    “date”:{
    “regex”:”/^\[0-9]{1,2}\/\[0-9]{1,2}\/[0-9]{4}$/”,
    “alertText”:”Date invalide, format JJ/MM/AAAA requis”},
    “onlyNumber”:{
    “regex”:”/^[0-9\ ]+$/”,
    “alertText”:”Seuls les chiffres sont autorisés.”},
    “noSpecialCaracters”:{
    “regex”:”/^[0-9a-zA-Z]+$/”,
    “alertText”:”Aucune caractère spécial n’est autorisé.”},
    “onlyLetter”:{
    “regex”:”/^[a-zA-Z\ \’]+$/”,
    “alertText”:”Seules les lettres sont autorisées.”}

  2. Great script. Looks like you left out the function to handle the email validation but it was pretty easy to figure out how to add it in. Thanks!

  3. On a second note, tying it in with a field that isn’t required is a bit tougher. I’d like to validate an email address only if it not empty. How would that work?

  4. There is an email verification, you mean server side?

    In the new version it will be possible to call the validation function spontaniusly yourself, I am actually working on it, but it is longer than I tought

  5. Hey Cedric Dugas,

    I am new to ajax and I can’t seem to get the ajax success function call correct. This is the success part in the js file: success : function() { callSuccessFunction()},
    in the html part, this is the function:
    function callSuccessFunction() {

    //remove all the class add the messagebox classes and start fading
    $(“#msgbox”).removeClass().addClass(‘messagebox’).html(”).fadeIn(1000);
    //check the username exists or not from ajax
    $.post(“ajax_login.php”,{ user_name:$(‘#username’).val(),password:$(‘#password’).val(),rand:Math.random() },
    function(data)
    {
    if(data==’yes’) //if correct login detail
    {
    $(“#msgbox”).fadeTo(200,0.1,function() //start fading the messagebox
    {
    //add message and change the class of the box and start fading
    $(this).html(‘Logging in…..’).addClass(‘messageboxok’).fadeTo(900,1,
    function()
    {
    //redirect to secure page
    document.location=’secure.php’;
    });
    });
    } else {
    $(“#msgbox”).fadeTo(200,0.1,function() //start fading the messagebox
    {
    //add message and change the class of the box and start fading
    $(this).html(‘Your login detail sucks…’).addClass(‘messageboxerror’).fadeTo(900,1);
    });
    }

    });
    return false; //not to post the form physically
    }

    It is not being called, rather just reloads the page when submit button is clicked.
    Please help thanks in advance.

  6. I believe that // CLOSE PROMPT WHEN ERROR CORRECTED part of the plugin needs some changes – I was today trying to make your plugin to work with WordPress Contact Form 7 plugin and I went through hell 😉

    One of the biggest issues was that your plugin was removing form elements, because CF7 surrounds them with span elements with class names as name/id attributes of input elements… anyways I believe that removing DOM elements like this:

    closingPrompt = $(caller).attr(“id”)
    $(“.”+closingPrompt).remove()

    is really risky. I think it would be better if you added some extra suffix so that there wont be a chance for this kind of problems, for example first set element of prompt like attr(‘id’)+validationForm
    and then
    closingPrompt = $(caller).attr(“id”)+validationForm
    $(“.”+closingPrompt).remove()

    besides that its a wonderful plugin, I love it!

  7. @chodorowicz, Good point I will add that, I am looking to alternative way, like wrapping the input with the error, however, this is not ideal, and with some options i tried before, I had a lot of surprises with frameworks

  8. Thanks for the great script!
    I am put this inside a jQuery ui-tabs and I have a problem when I switch to another tab, the error message from the previous tabs remain on the screen. Can someone tell me what I should do to turn them off when I switch tabs…. thanks in advance!

  9. @Pigfarm This is not currently possible with 1.3, if you send me your email I can send you the 1.4 beta when you can call the close function in javascript yourself when you change of tabs,

    Of course as you are using the UI tabs you probably will need to add events on click of your tabs outside UI.

    I am currently testing ajax validation but the rest is fine.

  10. That sounds excellent… I would love to try out the ajax validation. I am new to this site, could you tell me where I should send my email to you? Thanks again.

  11. @Cedric Dugas ah, I’m not sure what’s you policy on translations, are you planning on including them with the plugin? if yes I can send a polish translation to you if you’d like

  12. Forgive me for a “novice” question, but I have another script that runs onsubmit, and what I’d like to do is only run that one if your script does not find any unvalidated fields.

    So is there a way that I can cause yours to run from an onclick event from an input button, and then have your script actually submit the form if it finds no problems?

    Thanks for your time!

  13. well you can do it onsubmit, but not for blur event (IE each field) without modifying the code,

    Use the ajax success function described here : instead of false add: function(){ YOURFUNCTION() }

  14. Thanks for the quick reply, Cedric. Here’s the thing… I do not want your script to run from the form’s onsubmit event, I want it to run from an onclick event. Is that possible without major code changes?

  15. Is there a way I can manually trigger validation of a specific input? I presently got a form with select element and multiple inputs coming after it. Depending what you select I got some stuff appearing between the select and the input. So if the user go and click submit without selecting anything or typing anything it triggers the error messages. Then the user selects something and the stuff that should appear between the select and the inputs does appear pushing down the input but not the error messages. If I could trigger the validate of each inputs coming after the select box I could have them re-validate after a selection is made which would reposition the error message box.

  16. prashanthganathe@gmail.com
    This is a great script and already implemented in my project..
    As Jean-Michel asked before i have same issue…
    Actually i have a buttton which on clicking using jquery ajax

    $(‘#btnSociete’).click(function() {
    var msg = null;
    $.ajax({
    type: “POST”,
    url: “http://localhost/CRM_Contact_Focus/Home.aspx/GetSocieteInfo”,
    data: “{}”,
    contentType: “application/json; charset=utf-8”,
    dataType: “json”,
    success: function(msg) {
    $(‘#_Message’).overlay({ showMessage: true, icon: true, text: msg.d });
    },

    i need to update a div… but since on click the jquery will execute the serverside code… http://localhost/CRM_Contact_Focus/Home.aspx/GetSocieteInfo
    how can we validate all the controls on the button click like we can use ValidationGroup in Asp.net Validation controls.

    Even if this is the limitation of this script, still there are many reasons to use this great script. Thanks for sharing, we would be more than glad if we have some solution for this issue too.

    prashanthganathe@gmail.com

  17. Has anyone thought about tackling a custom message option for this script? I’m not the best with JavaScript, but I may give it a whirl when I find some time. It would be nice to be able pass in a custom message to be displayed if the input field is required and not filled in.

  18. Correct and good Portuguese translation (PT-PT):

    (function($) {
    $.fn.validationEngineLanguage = function() {};
    $.validationEngineLanguage = {
    newLang: function() {
    $.validationEngineLanguage.allRules = {“required”:{
    “regex”:”none”,
    “alertText”:”* Este campo é obrigatório”,
    “alertTextCheckboxMultiple”:”* Escolhe uma opção”,
    “alertTextCheckboxe”:”* Esta caixa é obrigatória”},
    “length”:{
    “regex”:”none”,
    “alertText”:”* Entre “,
    “alertText2″:” e “,
    “alertText3″:” caracteres”},
    “minCheckbox”:{
    “regex”:”none”,
    “alertText”:”* Número maximo de caixas marcadas foi ultrapassado”},
    “confirm”:{
    “regex”:”none”,
    “alertText”:”* O campo não corresponde com o outro”},
    “telephone”:{
    “regex”:”/^[0-9\-\(\)\ ]+$/”,
    “alertText”:”* Número de telefone inválido”},
    “email”:{
    “regex”:”/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/”,
    “alertText”:”* Endereço de email invalido”},
    “date”:{
    “regex”:”/^[0-9]{4}\-\[0-9]{1,2}\-\[0-9]{1,2}$/”,
    “alertText”:”* Data inválida, o formato tem que tar em YYYY-MM-DD”},
    “onlyNumber”:{
    “regex”:”/^[0-9\ ]+$/”,
    “alertText”:”* Apenas números são permitidos”},
    “noSpecialCaracters”:{
    “regex”:”/^[0-9a-zA-Z]+$/”,
    “alertText”:”* Não são permitidos caracteres especiais”},
    “onlyLetter”:{
    “regex”:”/^[a-zA-Z\ \’]+$/”,
    “alertText”:”* Apenas números são permitidos”}
    }
    }
    }
    })(jQuery);

    $(document).ready(function() {
    $.validationEngineLanguage.newLang()
    });

  19. You could add the plugin to a github repository, that way it would be easier to merge contibutions =)

  20. I am not seeing where the form information is being sent to – when they click send – I would assume its going to someones inbox – help – I would love to use this – its awesome
    Can I leave my email? rob@michaelsondesign.com

  21. @Cedric: great to hear a future version will have the ability to call the function spontaneously…I load a some forms via ajax on user actions after the page has loaded so being able to call the function once the form has been brought in will be very useful.

  22. Hi, Excellent work and a good time saver for any web developer…
    There’s somethings I think it can make it better,
    first of all I have a problem with the date validation and it is when you didn’t put the “required” option for you date input it will not let the form to be accepted if the date is not entered.
    and the second one is the position of the alert div… if there was an option for the horizontal position of the alert or at least the “left” or “right” side of it there was so excellent cause when we have a small size form and two inputs like date with a error description of 2 or more lines there will be a disaster when 2 of them are visible…
    thank you

  23. Email validation not working for ssss@ssss .patterns are not exactly matching after eval…..

    Great Job…

    Shijin menon

  24. I found a solution for the problem of accept of the non required text fields.
    let me explain again : When you add a rule to a text field ( e.g onlyNumbers or onlyLetters) without the “required” rule there must not be any error and the form must do submit if the text field was empty but a error will come up! ( e.g “* Numbers only” for onlyNumbers rule ).
    I did some change to the regular expressions and this problem is solved with this changes:
    “required”:{
    “regex”:”none”,
    “alertText”:”* This field is required”,
    “alertTextCheckboxMultiple”:”* Please select an option”,
    “alertTextCheckboxe”:”* This checkbox is required”},
    “length”:{
    “regex”:”none”,
    “alertText”:”*Between “,
    “alertText2″:” and “,
    “alertText3″: ” characters allowed”},
    “minCheckbox”:{
    “regex”:”none”,
    “alertText”:”* Checks allowed Exceeded”},
    “confirm”:{
    “regex”:”none”,
    “alertText”:”* Your field is not matching”},
    “telephone”:{
    “regex”:”/^([0-9\-\(\)\ ]+)*$/”,
    “alertText”:”* Invalid phone number”},
    “email”:{
    “regex”:”/^([a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4})*$/”,
    “alertText”:”* Invalid email address”},
    “date”:{
    “regex”:”/^([0-9]{4}\-\[0-9]{1,2}\-\[0-9]{1,2})*$/”,
    “alertText”:”* Invalid date, must be in YYYY-MM-DD format”},
    “onlyNumber”:{
    “regex”:”/^([0-9\ ]+)*$/”,
    “alertText”:”* Numbers only”},
    “noSpecialCaracters”:{
    “regex”:”/^([0-9a-zA-Z]+)*$/”,
    “alertText”:”* No special caracters allowed”},
    “onlyLetter”:{
    “regex”:”/^([a-zA-Z\ \’]+)*$/”,
    “alertText”:”* Letters only”}
    }
    I hope it helps!

  25. Is there any way to put the validation rules into my form fields without loosing HTML-validity? Maybe by replacing the brackets and commas in the class by allowed characters or by using ‘onchange’ to invoke the inline-validation?

  26. replace email reg-ex with /^([\w.])+\@(([\w])+\.)[a-zA-Z0-9]{2,}/ so the script will check for a dot (.) and some text at the end of email address

    great script, thatnks

  27. Feature Requests:
    In my form I split phone number to 3 separate fields. Currently I get 3 overlapping messages that the fields are required. I would love someway to group those 3 fields together and get only one error message.
    Secondly, my forms run in a popup window. Because the error message is aligned to the right side of the field, it can overlap and run outside of my popup. Any options to help position better would be awesome.

  28. Bravo! Love the new updates, however, any new fields I create on the form (client-side) aren’t automatically checked when the input changes. On submit, however, it still works.

  29. I love this plugin. Unfortunately you ‘re not gonna develop a function to check whether a username is used. Would you please reconsider? Or maybe use JSON? Thanx in advance.

  30. unfortunately I am not that good in php and it would not serve most of you to use a poorly designed username checker from DB, I give you the tools to do it in my validateUser.php , but I am pretty sure it would be easy to find something like this in php with google.

  31. Russian 🙂

    allRules = {“required”:{ // Add your regex rules here, you can take telephone as an example
    “regex”:”none”,
    “alertText”:”* Обязательное поле”,
    “alertTextCheckboxMultiple”:”* Выберите значение”,
    “alertTextCheckboxe”:”* Обязательный выбор”},
    “length”:{
    “regex”:”none”,
    “alertText”:”* Обязательная длина от “,
    “alertText2″:” до “,
    “alertText3″: ” знаков”},
    “minCheckbox”:{
    “regex”:”none”,
    “alertText”:”* Обязателен выбор”},
    “confirm”:{
    “regex”:”none”,
    “alertText”:”* Поля не совпадают”},
    “telephone”:{
    “regex”:”/^[0-9\-\(\)\ ]+$/”,
    “alertText”:”* Неверный номер телефона”},
    “email”:{
    “regex”:”/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/”,
    “alertText”:”* Неверный mail”},
    “date”:{
    “regex”:”/^[0-9]{4}\-\[0-9]{1,2}\-\[0-9]{1,2}$/”,
    “alertText”:”* Дата должна быть в формате YYYY-MM-DD”},
    “onlyNumber”:{
    “regex”:”/^[0-9\ ]+$/”,
    “alertText”:”* Только цифры”},
    “noSpecialCaracters”:{
    “regex”:”/^[0-9a-zA-Z]+$/”,
    “alertText”:”* Недопустимы спецсимволы”},
    “onlyLetter”:{
    “regex”:”/^[a-zA-Z\ \’]+$/”,
    “alertText”:”* Допустимы только буквы”}
    }

  32. I have been trying to validate file input extensions using regex

    “image”:{
    “regex”:”/^.*\.(jpg|JPG|jpeg|JPEG|gif|GIF|)$/”,
    “alertText”:”* Invalid phone number”},

    But I can’t get this to work. Can this plugin do this?

    Cheers,
    Doug

Comments are closed.