Since 2.0 a lot of people wondered how was working the new ajax validation. Doing ajax validation and controlling the submit form event has always been an headache, and while the validation engine aspire to make it as easy as possible, it is probably never going to be simple for junior developers.

To be fair, the ajax feature has been rewritten and was not as mature as in the 1.7 version. However the 2.x base code is starting to be pretty good with the recent updates. If no other bugs popup, I will start tagging the 2.x releases on github and this version will be considered stable for a while.

There is 2 demos added to the repository, one with only the inline validation and another with the inline and submit ajax validations used together.

Inline Ajax Demo
Submit & Inline Ajax Demo
Download

2 types of ajax validation, first the inline validation

The inline validation calls a file every time someone changes a field, a good example would be checking if a username is available on the blur or keyup event. The inline validation is not called on submit. The inline ajax validation is meant to interact with your users directly, you will have to verify the information on submit too.

We made the decision to clearly separate those 2 concerns, the behavior of inline ajax validation used on submit event was not clear to us (should it submit directly after or not?, etc..) and imposing one sounded like a not so good idea. This means that you will have to share the validation on those 2 events.

So, first you need to setup the inline validation rules in the language file:


"ajaxNameCallPhp": {
// remote json service location
"url": "phpajax/ajaxValidateFieldName.php",
// error text
"alertText": "* This name is already taken",
// success text
"alertTextOk": "* This name is available",
// speaks by itself
"alertTextLoad": "* Validating, please wait"
}

Once it is setup, you need to add this rule in the field class validation : ajax[ajaxNameCallPhp].

Ok, so the easy part is done, you have the inline validation working on the front-end. Now this will send the field in ajax to the defined url, and wait for the response, the response need to be an array encoded in json following this syntax: [“id1”, boolean status].

So in php you would do this: echo json_encode($arrayToJs);

Obviously you will need to actually do something with the fields in php to validate it, but this is up to you. At this point you should be able to change the boolean value and see the error prompt appear. If you have problem understanding, look at the example in the demos included with the script.

AJAX Submit Validation & sending data

The ajax validation is executed when all the fields are validated, but like a said before, the inline validation will not be executed. The ajax submit validation is just your complete form submitted in ajax, so you can manipulate the data how you want.

I think it is important to note that if you only want to send your data in ajax and not use the error callback from the validation engine, using onValidationComplete will give you more power and maneuverability, but I am not going to go into that, please check the doc on github, it’s pretty straight forward.

So, submit Ajax Validation

You setup the ajax submit validation when you are instancing the plugin, a good example would be :


jQuery("#formID").validationEngine({
ajaxFormValidation: true,
onAjaxFormComplete: ajaxValidationCallback,
onBeforeAjaxFormValidation: beforeCall
});

ajaxFormValidation: mean that the form will always submit in ajax
onBeforeAjaxFormValidation: Do something before the submit ajax validation
onAjaxFormComplete: Do something when the request comes back

By default, you can return a json encoded array with back-end validations that are not succeeding to be interpreted by the validation engine, obviously the engine will show error prompts in that case. You need to follow this pattern:
[[“id1″, boolean,”errorMsg”],[“id2”, false, “there is an error “],[“id3”, true, “this field is good”]]

The future

I hope it will help you guys understand better the ajax feature, for the future I want to add external hooks (using jQuery trigger event) into the engine, and obviously, squash bugs.

In fact some of the triggers are already there but not in the doc yet ;).

If you find bugs in the current release don’t forget to add them on github and if you like the plugin, mentioning the project in your social networks is always appreciated!

59 thoughts on “Using form ajax validation with the jQuery Validation Engine plugin

  1. I can’t seem to get this to work. I have a form with a “fee” text input with id “fee”. The form id is “form”. I have:

    $(document).ready(function() {
    // … a bunch of other stuff that works fine, including the non-ajax validationengine stuff … //
    $(‘#fee’).addClass(‘validate[required, ajax[ajaxUserCallPhp]]’);
    $(‘#form’).validationEngine({ajaxFormValidation: true});
    });

    In jquery.validationEngine-en.js, which is copied from this demo and has only this section edited:

    “ajaxUserCallPhp”: {
    “url”: “/fee.cgi”,
    “alertTextOk”: “VALID”,
    “alertText”: “NOT VALID”,
    “alertTextLoad”: “Validating…”
    },

    and fee.cgi, which is in perl and works fine in the browser, is simply:

    #!/usr/bin/perl
    print “Content-type: text/html\r\n\r\n[\”fee\”,true]”;
    exit;

    I never see “validating…” or “VALID” or “NOT VALID.” Totally stumped here, and about to give up…

    1. Ahh, ignore that. I hadn’t grasped that it doesn’t ajax validate until you either click out of (blur) the form field OR submit *with no other validation errors.* I had other invalid fields and was expecting it to also tell me about the invalid ajax ones at the same time.

    2. Same here. Version 1.7 worked, but this one does nothing when ajax validating a field with a remote URL call.
      I use it for a captcha field class=”validate[required,ajax[ajaxCaptcha]] text-input” and added this custom edit to the JS

      “ajaxCaptcha”:{
      “file”:”captcha_check.asp”,
      “alertTextOk”:”* OK”,
      “alertTextLoad”:”* Checking…”,
      “alertText”:”* Wrong code”}

      But no luck. It’s only checking whether or not the field is empty

  2. Ok. One hint for the problem solution. Downloaded the package attached to this article and IT WORKS. It’s the 2.1 version… The problem was with the 2.0

    Now it’s ok, thanks.

  3. Sorry for my many comment, but maybe they can be useful for other people.
    Another thing changed since 1.7: validateValue is not fieldValue in querystring passed to validate URL.
    Finally got the checking working, the problem now is that the “invalid code” message doesn’t make the submit button to blind. In other words the output message when checking the field is OK, but it doesn’t stop the form from being submitted

      1. Hi tiny,

        I can help you if you send my your email,

        If you read the article thoroughly you will see that the inline validation is no longer used on submit,

        You need to share the validator with your submit rule, in the case of the submitPHP example, it get validated in ajaxvalidatesubmit

  4. Hi Cedric,
    great work, thank you!
    I found the italian localization was out of date so i made a new translation, you can mail me if you need it: i think it can be confusing as there are still reference to “file” values in the ajax calls.

    Now, a question: why, in the file jquery.validationEngine-en.js there are

    “ajaxNameCall” and “ajaxNameCallPhp”
    and also
    “ajaxUserCall” and “ajaxUserCallPhp”

    I think the ones without Php in the end are old functions, isn’t so?

    Thanks again!
    Nicola

  5. Hi Cedric,

    Great plugin! I’m a bit muddled when it comes to javascript, and I need to edit the script to show only the first error onSubmit rather than all errors. What and where do I change this? Help is greatly appreciated!

    Thanks,
    Audrey

  6. Hi,

    Sorry but currently you can’t only show the first error,

    You could do a loop using validateField, but that would be kind of a hack

  7. Hello i have found a minor bug with the radio groups. The alert popup didn’t close when a radio was selected.
    So i juste added the code :
    form.find(“[class*=validate][type=radio]”).bind(“click”, methods._onFieldEvent);

    at line 57

    Thanks for this great tool
    Ogan

  8. Bonjour Cedric,

    Content de voir que je ne suis pas le seul de Montréal… 😉

    Alright in english now so people could understand too…
    I really love your validation engine since it’s very well designed, though I’m new to JQuery and I’m trying your AJAX part but there’s 2 things that cross my mind fast fast:

    1- I’m not comfortable having to edit the “jquery.validationEngine-en.js”, I would rather have my own file to do that, so any new Rev from your side would be flawless. But maybe since I’m new to JQuery, I just don’t know how to do that part…

    2- I’m trying to edit your PHP test file “ajaxValidateFieldUser.php”, so I could instead put the error msg from there as you mentionned earlier and so I’ve added this: $arrayToJs[2] = $validateSuccess; … so it is the 3rd parameter, it takes it but never display it whatsoever. Am I missing something?

    Really love your package
    Merci
    Ghislain

  9. Hi,

    currently, if I am not mistaken, you can only specify that on the submit validation, so for the inline ajax that unfortunately need to be changed in the localization file.

    For now anyway, might come as a feature later

    1. Thanks for your quick reply Cedric,

      I’m actually trying to make a validation for a Login page, and I’m breaking my head on how to pass the value of my previous username field to the PHP script as the “extraData”. I will probably use the submit validation type. Just need to know how to pass something that is not defined when validation is created…

      Thanks for your help, really appreciate

  10. Yea submit will submit the entire form and you can pass extradata, but its not dinamic for now.

    Something we want to change

  11. Hi Cedric,

    many thanks for this very usefull jquery extension, it helped me very much! Good work!

    I have one suggestion, it would easy for one or another person, at least me, to add rules to the language specification at runtime from within my javascripts.

    Because i don’t have all translations yet at hand I actually found a problem to update all the language files for my multilingual platform with the specific ajax calls i would like to use. The problem with the current situation is, that i can’t use my build-in translation functionality. I use gettext to translate texts at runtime and poedit to let translators making the translations once before a version gets released. Poedit easy the process of translation for the translators because the persons see only the original and the target translation per poedit file. However, i am sending every translator one translation file per language and i would like to keep that workflow.

    A solution for me would be to allow in the initialization process to hook or extend the currently used language file with my ajax calls. The translations are coming than from my poedit files and not from the validator language file.

    I hope my suggestion is a little bit clear!?

    Kind regards,

    Markus Siebeneicher

  12. Hi Cedric — Great plugin! I’ve tried many jQuery validation plugins and this is the best.

    I’m moving from 1.7 to 2.1 and I’m having trouble with the inline ajax validation. When I browse to my php validation directly using the url variables exactly as they are sent by the validation engine (copied the url from firebug) I get the correct responses, but when I try to validate my form field I will always get a green “Available” prompt. My custom ajax rule is:

    “ajaxSKU”:{
    “url”:”validateSKU.php”,
    “alertTextOk”: “* This SKU is available”,
    “alertText”: “* This SKU is already taken”,
    “alertTextLoad”: “* Validating, please wait”
    }

    I really appreciate any help you could provide.

    Thanks,
    Jim

    1. Do you have your example online? I think its probably because 1.7 server response changed a bit.

  13. Hey, I just wanted to say thank you. It was a easy install and quite easy to understand as well. It was up and running in less than a half a hour.

    Kev

  14. Hello,
    let me say I really love your plugin!

    I have a weird problem though, when using your plugin on a page with lots of divs (multiple z-indexes, floats etc), scrolling the page makes the validation “bubbles” lose their positioning above the form fields and they just start scrolling along the page with the rest of the content. Have you got any idea why this would happen?

    1. -Note: Even if I try isOverflown:true and set the overflownDIV to the one the form is in, nothing happens. On top of that, when I do both of those things above, the validation popup(s) appears on top of the div, not at their correct position at the form fields.

  15. Hi Cedric, firstly I just want to thank you for this masterpiece code for form validation. It is absolutely amazing and easy to work with. I am a newbie developer and I need some help with the code to get my AJAX validation and form submit working correctly. I have read your articles endless amount of time and gone through the comment to try to resolve the issue but I just cannot understand without examples.

    I need someone to review my code and advise me what is missing.

    Here are my codes:

    [ form input & header ]
    **************************

    jQuery(document).ready(function(){
    jQuery(“#formID”).validationEngine({
    });
    });

    [ jquery.validationEngine-en.js ]
    ———————————————

    “ajaxUserCallPhp”: {
    “url”: “phpajax/ajaxValidateFieldUser.php”,
    “alertTextOk”: “* This username is available”,
    “alertText”: “* This user is already taken”,
    “alertTextLoad”: “* Validating, please wait”
    },

    [ ajaxValidateFieldUser.php ]
    ——————————————

    $validateValue=$_GET[‘fieldValue’];
    $validateId=$_GET[‘fieldId’];
    $validateError= “This username is already taken”;
    $validateSuccess= “This username is available”;

    /* RETURN VALUE */
    $arrayToJs = array();
    $arrayToJs[0] = $validateId;

    /*Database Config+Connection*/
    $username = “root”;
    $password = “”;
    $hostname = “localhost”;

    $dbhandle = mysql_connect($hostname, $username, $password) or die(“Unable to connect to MySQL”);
    $selected = mysql_select_db(“etsy”,$dbhandle) or die (“Could not select schema”);
    $sql_checkusername = “SELECT user_login FROM user_data WHERE user_login=’$validateValue'”;
    $result=mysql_query($sql_checkusername );
    $count=mysql_num_rows($result);

    if($count>=1){
    $arrayToJs[1] = false; // RETURN false
    echo json_encode($arrayToJs); // RETURN ARRAY username is taken
    } else {
    for($x=0;$x

    [ My Problem ]

    Inline form validation to check the username availability in the database is working fine. If the username is not available, error prompt shows up correctly. However, the form will still submit even the username is not valid.

    I just don’t know how to trigger the code to check for all inline validation on submit call. Please help me, I am very new to Jquery and need some guidance. Thank you thank you very much.

    1. MMK, have you found a solution to this problem? I have the exact same problem.

      All the validation works great using the inline technique but the form will submit even though this plugin sees the field is invalid.

      Any help would be great 🙂

      1. Until Cedric can come up with a more permanent fix to allow the inline AJAX validation to actually register as a non-validated field when submitting a form I’ve found a relatively simple workaround. It isn’t super pretty but it works like this:

        My forms action POSTS to to $PHP_SELF.

        At the top of my code i’ve wrapped an errors array into my form processing that explicitly stops the form from submitting while validating the same field(s) a second time. It looks a bit like this:

        $arrErrors = array();
        if (!empty($_POST[‘submit’])) {
        $field = $_POST[‘filednametovalidate’];
        $query = “SELECT `fieldindb` FROM `table` WHERE `fieldindb` = ‘{$field}’
        $results = mysql_query($query) or die(mysql_error());
        if(mysql_num_rows($results) == 0 {
        $arrErrors[‘fieldnametovalidate’] = ‘This field is not valid, try again!’;
        }
        if(count($arrErrors == 0)) {
        ** do your db INSERTS/UPDATE/ETC **
        } else {
        foreach ($arrErrors as $error) {
        echo “$error”;
        }
        }
        }

        I hope this helps anyone else looking for a solution! jQuery Validation Engine is an awesome project and I’m sure Cedric (and others) will work out the kinks soon enough!

  16. Ops, missed out some part of the code.

    [ ajaxValidateFieldUser.php ]

    if($count>=1){

    $arrayToJs[1] = false;
    echo json_encode($arrayToJs);

    } else {

    for($x=0;$x<1000000;$x++){
    if($x == 990000){
    $arrayToJs[1] = true;
    echo json_encode($arrayToJs);
    }
    }
    }

    include 'include/database_disconnect';

  17. I have the some problem.
    Inline ajaxUserCallPhp work fine with red message, but the form will still submit even the username is not valid.

    Bye.

  18. Hi, I’m working with ASP.NET and I’d like to use the ajax inline validation, the question is, the url location would be the path to a web service/web method (service.asmx/method) location? Do you guys have done anything similar?

    Thanks

    1. I would like to know the answer of this please help us. im using asp.net and what to use the inline and form ajax valditon of the said plugin.

  19. Using your form validator in above mentioned website, but, i cant get it to accept cyrillic. I did create a ru.js file for the validation, but even so, if i type cyrillic characters i get the message it just wanst characters. And then, if i can get it to submit, the cyrillic characters in the comment (no-validation-field) are all garbage when received in my email.
    I was looking for the forums, to find support on this, but… where is the forum? 🙂

    So, is it possible to use this code with cyrillic, and make it to submit cyrillic in the sent email?

  20. hai.. how validtionengine can be used for ajax…
    this is the sample my code

    $(document).ready(function() {
    $(‘#formID’).submit(function() {
    $.ajax({
    type: ‘POST’,
    url: “insertdata.php?aksi=insert”,
    data: $(this).serialize(),
    success: function () {
    var options = $.extend({title: “EDIT DATA SURAT JALAN NO “}, options || {});
    var dialog = new Boxy.load(“tampil_after_ins.php”, options);
    return false;
    }
    })
    return false;
    });
    })

  21. How I can confirm to me one by one, just show me one by one when you send, after correcting the first error, and resubmit the second correct me .. I do not like to show me all the time is very ugly .. thanks

    gracias por la respuesta….

  22. Great validation, but since I have a datepicker I have found it to be almost useless. It will prompt an error when you pick your date, since it registers that you make the element inactive, by clicking outside the element (when you pick the date).

    Is there a solution for this issue, or is it just not for people with a datepicker?

  23. an You Give Me The Code For “ajaxValidateFieldUser.php”

    what i have to write code in “ajaxValidateFieldUser.php”

  24. Hello!

    I’m trying to implement validation in a previous form I had, that is submited through ajax. I do not want to usse ajax validation I just want to use ajax to submit the data. Here’s the actual code (not working, post is done even if the form is not valid):

    /* attach a submit handler to the form */
    $(“#form_mensagem”).submit(function(event) {

    /* stop form from submitting normally */
    event.preventDefault();

    /* get some values from elements on the page: */
    var nome = $(this).find( ‘input[name=”nome”]’ ).val();
    var email = $(this).find( ‘input[name=”email”]’ ).val();
    var mensagem = $(this).find( ‘textarea[name=”mensagem”]’ ).val();
    var url = $(this).attr(‘action’);

    /* Send the data using post and put the results in a div */
    $.post(url, {
    nome: nome,
    email: email,
    mensagem: mensagem
    }, function(data) {
    $(“#caixa_mensagem”).html(data);
    });
    });

    $(“#form_mensagem”).validationEngine({
    scroll: false,
    });

    Any help?

  25. Also tried this, but no success again:

    $(“#form_mensagem”).validationEngine({
    scroll: false,
    });

    $(“#form_mensagem”).validationEngine(‘attach’, {
    onValidationComplete: function(form, status){
    /* get some values from elements on the page: */
    var nome = form.find( ‘input[name=”nome”]’ ).val();
    var email = form.find( ‘input[name=”email”]’ ).val();
    var mensagem = form.find( ‘textarea[name=”mensagem”]’ ).val();
    var url = form.attr(‘action’);

    /* Send the data using post and put the results in a div */
    $.post(url, {
    nome: nome,
    email: email,
    mensagem: mensagem
    }, function(data) {
    $(“#caixa_mensagem”).html(data);
    });
    }
    });

  26. @Piet Degeling wrote:Is it possible to use this code with cyrillic, and make it to submit cyrillic in the sent email?

    Yes. I use Serbian cyrillic. You need to use UTF-8 encoding.
    1. Save your language file (ru.js) with “UTF-8 without BOM” encoding.
    2. Other files need to use UTF-8 encoding too.

    That`s it.

  27. I am using the Jquery validtionengine and Seems not able to get it work. the message Validating,please wait remains the whole time. It does not turn either green or red as per example. I am using ColdFusion.

    The call to a dataabse is completed as return the valid result but the message does not get changed. Please help

  28. for the form validation. If I have a dynamic form so I do not know what fields will be there how can I submit the form

    1. it can validate by form id. use it..

      and define fields id dynamically..

      it will work..

  29. Pls, This is Urgent. i am a new commer to jquery…please i have this issue and hope you can help me out.
    1. i have a php script that dynamically prints out text boxes based on a database value
    1a i also have a php form that collects all the input and puts in a db.

    2. i have added your wonderful validation script to the page, bt my problem is..i want it to call my php insert page(page 1a) each time i tweak the the AjaxValidation Page to include my code, nothing happens…please help

  30. i have some problem with inline validation, the control work fine and show error if username exists but the form go on submit…you have found some solutions?

    1. Hi,

      I have same problem .. that even though ajax name validation fails (error popup displays fine), its not stopping from submitting form ..

      can u plz help on this

      thks

  31. i have found a solutions for this problem but i tried to do my solution but not work because i I have made sure some mistake in the js code. we must send form on phpself saving form values and put it in the values of fields,
    for example:

    <input type="text" id="name" name="name" value="” />

    and when isset $_POST, if there are some error in the form we must call method for validate form automatically when the page is load, this method in default called on mouseclick probably, i need to make new method to call validate funcion on init in the header of the page only if are set $_POST…someone can show me how to create this method in js? the part on php is already finished end it work good…

    this is my code:

    if(isset($_POST[‘button_name’]))

    {
    echo ‘

    jQuery(document).ready(function(){
    jQuery(“#validate”).validationEngine(“NEW METHOD”,{
    promptPosition : “centerRight”,
    scroll: false

    });

    });

    ‘;}

    else

    {
    echo ‘

    jQuery(document).ready(function(){
    jQuery(“#validate”).validationEngine({
    promptPosition : “centerRight”,
    scroll: false

    });

    });

    ‘;}

    do you think this can work fine?

  32. Hi

    I love your validation engine, has helped me add some nice validatoin to a project I am working on at the moment.

    One question, how would I create a rule to check that a user is at least 18 years old, based on a date of birth field?

    Thanks

    Mark

  33. I am trying to write a zip code function (5 digits) and to modify the phone number to just 999-999-9999.
    I am having absolutely no luck.
    Everything else works fine so I am not sure why?
    This is the zip code example which I put into the validationEngineLanguage.

    “zipcode”: {
    “regex”: /^([0-9]{5})$/,
    “alertText”: “Invalid Zip Code”
    },

    best validation query out there! Wonderful job.

  34. Hi, I discovered your script two days ago and until now I don’t get it works fine!
    I uncomment the 2 lines in the demoAjaxSubmitPHP.html to submit the form, but the result is always:

    [[“user”,false,”This user is already taken”],[“firstname”,false,”This name is already taken”]].

    Where are the values of fields user and firstname? There is a way to show a modal message like “Your form is sent!” after press submit button?

  35. Hi All,

    I have same problem that, even though ajaxNameCall working fine to check name existence ..still the form submit was happening ..

    i backtracked it … the $(form).validate() returning TRUE for both name exists and for non-existence.. that’s why ..

    But still problem remains .. how to resolve this ..any ideas appreciated.

    Thanks

  36. HELP.. working this for many days but my php submit wont validate.. it will always say validating please w8…

    mysql_connect(“localhost”, “root”, “”) or die(mysql_error());
    mysql_select_db(“sample”) or die(mysql_error());

    /* RECEIVE VALUE */
    $validateValue=$_GET[‘fieldValue’];
    $validateId=$_GET[‘fieldId’];

    $validateError= “This username is already taken”;
    $validateSuccess= “This username is available”;

    /* RETURN VALUE */
    $arrayToJs = array();
    $arrayToJs[0] = $validateId;

    $sql = mysql_query(“SELECT username FROM registration WHERE username = ‘$validateValue’ “);
    $num = mysql_num_rows($sql);

    if($num != 1){ // validate??
    $arrayToJs[1] = true; // RETURN TRUE
    echo json_encode($arrayToJs); // RETURN ARRAY WITH success
    }
    else{
    for($x=0;$x<1000000;$x++){
    if($x == 990000){
    $arrayToJs[1] = false;
    echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
    }
    }

    }

Comments are closed.