If you’ve ever confronted the task of validating data in a form, you know about choice. Whether it’s choosing between client side or server-side scripts, or the amount of information a user should see on the screen, the results should always give the user quick and meaningful feedback, while providing a solution for when things go wrong.

HTML Form Builder

In the past, a good programmer wanting to do both would validate a form on the client side with say JavaScript for quick feedback, but needed to also create server-side validation scripts as a back-up in case things went awry with the browser. Unfortunately, JavaScript can’t use a PHP (or ASP) server-side validation function and vice versa. Because this redundancy adds to the development time on a project, some just do away with the quick feedback for the user and opt for the safe bet and validate on the server only.

Thanks to AJAX, we can provide real-time feedback to the user using server-side validation scripts and eliminate the need for redundant validation functions without giving up a solution that degrades gracefully when JavaScript is disabled.

How it Works

We’re going to start with the form in the html file, move on to the live feedback created by the JavaScript, and then finish up with the server-side validation functions.

The Files
If you want to follow along, we’ve got the files in ASP and PHP flavors for download.

The ASP zip contains the following files:

  • default.htm
  • validate.js
  • formvalidation.asp

The PHP zip contains the following files:

  • index.php
  • validate.js
  • formvalidation.php

Part 1 - The Form
Starting with the html file (default.htm/index.php), we need to create our form.

<form name="form1" id="form1" method="post"

The form needs to submit the data to ‘formvalidation.asp’ / ‘formvalidation.php’ page and pass variable ‘validationtype’ appropriately as ‘asp’ or ‘php’. This will ensure the form is validated on submission even if JavaScript is disabled. The ‘return validate();’ function is added unobtrusivly and prevents submission if there are any errors. This JavaScript function doesn’t actually do any error checking itself, but checks for error flags like an improperly formatted e-mail address on the page.

After the form is set up, we are going to attach ‘onBlur’ events to each field with unobtrusive javascript. ‘onBlur’ will then pass the input to ‘validateMe(). To learn more about attaching events unobtrusively with the class attribute, check out A Guide To Unobtrusive Javascript.

<input type="text" name="user" tabindex="1" id="user"
class="validate required none usermsg" /><input type="text" name="email" tabindex="2" id="email"
class="validate required email emailmsg" />

When ‘validateMe()’ is called ‘onBlur()’ live validation via AJAX is performed after splitting the input class into three variables:

  • *sRequired � determines if the field is required.

  • *sRules � determines the type of validation (eg. email).

  • gShow - the ID of the node that will display errors.

After the validation takes place, the feedback message needs a place to be displayed. The fourth word in the class or gShow represents the ID of where this feedback will be presented.

<td id="emailmsg" class="rules">Required</td>

The class is set to rules because we’re using css to set the color to red if there are erros present and black if not.

Part 2 - Real Time Feedback

var gShow; //holds node to display error msg
var url = "formvalidation.asp?validationtype=ajax&val=";var http = getHTTPObject();function validateMe(objInput) {sVal = objInput.value;  
sRules = objInput.className.split(' ');
sRequired = sRules[1];
sTypeCheck = sRules[2]; 
        gShow = sRules[3];"GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck, true);http.onreadystatechange = handleHttpResponse;


‘validateMe’ is called ‘onBlur()’ and splits the class in order to find the rules and error display node and passes that to the formvalidation.asp or formvalidation.php page to do the actual validating. From there the ‘handleHttpResponse’ function will take over.

function handleHttpResponse() {
  if (http.readyState == 4) {   //results is now the feedback from the asp page
   results = http.responseText.split(",");
   document.getElementById(gShow).innerHTML = "";

After the ASP or PHP page validates the field a feedback message is returned to the ‘handleHttpResponse()’ function. This feedback message is then appended to the error display node giving the user real time feedback.

Part 3 - The Validation

The heart of the process lies in the ‘formvalidation.asp’ or ‘formvalidation.php’ page. This script will take the value and rules, checks for problems, and sends back positive or negative feedback. First, we need to determine if we are validating client or server side.

sValidationtype = request("validationtype")
    gContinue = true    select case sValidationtype
      case "ajax"
      case "asp"
    end select
$validationtype = $_GET["validationtype"]; 
    $continueSubmit = true ;     switch ($validationtype)
    case 'ajax':
    case 'php':

Switch to: PHP ASP

The lines of code above determine how we’re going to validate. ‘ProcessAjax()’ will be called ‘onBlur()’ if javascript is enabled and emulate client side validation. ‘ProcessASP()’ or ‘processPhp()’ is called ‘onSubmit’ when the form is submitted and works like normal server side validation with or without JavaScript.

function ProcessAjax()      sVal = request("val") 'value of the textbox being validated
      sRequired = request("sRequired")' check if the field is required
      sTypecheck = request("sTypecheck")'additional validation rules       ' validateRequired checks if field is required 
      validateRequired sRequired, sVal, sTypecheck      ' check for other validation requirements
      select case sTypecheck
          case "date"
               ProcessAjax = validateDate(sVal)
          case "email"
               ProcessAjax = validateEmail(sVal)
       end select    end function
function ProcessAjax()
      $required = $_GET["sRequired"];
      $typecheck = $_GET["sTypeCheck"];
      $val = $_GET["val"];      //validateRequired checks if it is required
      validateRequired($required,$val,$typecheck);      //check for other validation requirements    
      switch ($typecheck)
        case 'date':
        case 'email':

Switch to: PHP ASP

‘ProcessAjax()’ takes in the value and rules of the field being validated. The different validation functions are called and will return feedback (eg. Thank you or Invalid Email!) to the ‘handleHttpResponse()’ function and from there to the form. This will all happen in real time.

function ProcessASP()      'request all of the forms variables
      sUser = request("user")
      sEmail= request("email")      ' check to see if the different form fields are valid      ' only use validateRequired if no other validation besides being
      required is necessary      validateRequired "required", sUser, "none"      ' use appropriate validation for other fields      validateEmail(sEmail) 'returns feedback      'if continue is not 0 then continue with the form submission
      if gContinue then
      'submit form or email or whatever you want to do
      end if    end function
function processPhp()
       //request all of the forms variables
       $user = $_POST["user"];
       $email= $_POST["email"];
       global $continueSubmit;       //check to see if the different form fields are valid       echo "Username: ";
       validateRequired("required", $user, "none");
       echo "<br />";       echo "Email: ";
       validateEmail($email)         //if continue is not 0 then continue with the form submission
        if ($continueSubmit){
         //submit your form
       }    }

Switch to: PHP ASP

‘ProcessASP()’ / ‘processPhp()’ is called when the form is actually submitted. Where ‘ProcessAjax()’ validates each field ‘onBlur()’, ‘ProcessASP()’ or ‘ProcessPhp()’ will validate the entire form after submission.

After requesting the fields we’ll validate them.

validateRequired "required", sUser, "none"
validateRequired("required", $user, "none")

Switch to: PHP ASP

Only call ‘validateRequired’ for fields that are required and have no additional validation requirements. ‘validateRequired()’ will return and write either a “Thank You” if it is valid or an invalid message if it is not.

validateEmail($email) ;

Switch to: PHP ASP

For validation of the email field call ‘validateEmail(sEmail)’ with sEmail being the field validated. It will also return a “Thank You” or invalid feedback message.

Validation Functions

Validate each field using similar syntax as the ‘validateEmail()’ function. Obviously, you can create your own functions to validate your specific fields. I would recommend The Regex Library for your regex validation expressions. I’m not going to go into the different validation functions, but the code in the zip files is well explained and extensively commented. Feel free to leave comments or email me if you have any questions or suggestions.

HTML Form Builder
Chris Campbell

Degradable Ajax Form Validation by Chris Campbell

This entry was posted 5 years ago and was filed under Features.
Comments are currently closed.


  1. pixelEngine · 5 years ago

    Brilliant.. thanks for making it in both asp and php versions and also available for dl!!!!

  2. Chris Campbell · 5 years ago

    No problem. Glad to hear it helped.

  3. Tim · 5 years ago


    Have only just started dabbling with AJAX and am currently thinking about writing a generic form validation and database entry script in PHP.

    Your tutorial has given me a few ideas to be getting on with.

  4. Jo · 5 years ago

    The validate function should have one small addition. At the end of the script, “gErrors = 0;” should be added.

    Because gErrors is global, the value does not reset to 0 and it will leave revalidated fields red that previously failed validation (i.e. not changing back to black).

    A very nice script otherwise.

    /2 cents

  5. wj · 5 years ago

    Hey, I am thinking why you are using javascript to call a php file to do the validation.

    For example, onblur=validateMe(). if you have some thing like below, it will validate the email address just the php file does and silently display the result besides the email box.

    function validateMe(val, rules, show) { gShow = show; function isEMailAddr(str){ var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/; if(!str.match(re)){ document.getElementById(gShow).innerHTML = “”; document.getElementById(gShow).appendChild(document.createTextNode(“Invalid”)); }else{ document.getElementById(gShow).innerHTML = “”; document.getElementById(gShow).appendChild(document.createTextNode(“Okay”)); } } isEMailAddr(val); }

    If you want to validate both username and email, you will need the ‘rules’ param.

  6. Ryan Campbell · 5 years ago

    The reason the validation is done on the server side is so it will work even if javascript is disabled, without the need to duplicate the validation functions on client and server.

  7. Kevin Hale · 5 years ago

    One change you may want to make to the setup is to go with Unobtrusive JavaScript. Instead of attaching the onblur or onsubmit in the HTML you can do it all in an external JavaScript file and attach the actions to the form elements by id.

    Chris Heilmann’s explanation at is one of the better explanations of how that can be done.

    Otherwise, well done and especially nice that you did it bilingually.

  8. Chris Campbell · 5 years ago

    Jo, I think I understand what you’re saying. Valid fields should turn back to black onblur if they are valid. Currently they turn black onsubmit if valid. That could be confusing to the user.

    You’re right, that would be a better way.

    Thank you both for the suggestions and I think I’ll try to implement the changes by sometime tomorrow.

  9. James Wilson · 5 years ago

    I think having server side AND client side validation both pivoting off of an XSD file defining the validation requirements is a better idea. This just seems sloppy.

  10. Ryan Campbell · 5 years ago

    I agree that this may not be the ideal solution, but it seems better than the way most people are currently validating with repetitive functions.

    There are a few ways to clean this up though if it feels sloppy. First, make the server side validation functions a class. That way, they will all be editable from a single file, and once they are written they are completely resuable. Next, structure the javascript in an object oriented manner, so that is completely reusable. That would leave you with two validation files that you can plug into any project, and the only change that would need to be made is adding an onblur to your fields and a handful of lines to the server side submit.

    Thanks for suggesting XSD though. I have not played with it that much, but now I am going to work with it some more.

  11. Kevin Hale · 5 years ago

    James, you get an ‘A’ for that’s actually a good idea and an ‘F’ in both manners AND useful information. For those interested in learning more about using XSD (or XML schemas) check it:

  12. James Wilson · 5 years ago

    I apologize if i was insulting, just trying to help.

  13. Chris Campbell · 5 years ago

    I took no offense James and appreciate the feedback. I actually spent the whole day looking at xsd. I’m wondering if there is a way to validate individual fields with it. All the examples I see validate the entire xml document and return either a pass or fail. I’d be interested to hear any ideas on how to use it for real time validation.

  14. Chris Campbell · 5 years ago


    Still looking at the different ways of making this type of script unobtrusive. Here’s a great article and discussion on the problems.

  15. Kevin Hale · 5 years ago

    Chris, Glad that you’re on it, I’ll take a stab at it as well and pass on any unobtrusive solutions I come up with. It’s one of those things that has been done badly for so long it’s hard to find good examples of JavaScript that is kept out of the markup.

    There are some functions for getElementByClassName instead of by id over at that may be useful for this.

  16. James Wilson · 5 years ago

    I reccomend XML Schema by Priscilla Walmsley (ISBN 0130655678), she goes in depth on how to do it.

  17. Chris Campbell · 5 years ago

    Thank you both for the suggestions. I found an interesting article at which uses xml for validation.

  18. raja · 5 years ago

    hai this good

  19. Neil · 5 years ago

    Truly amazing..

  20. Scrambled · 5 years ago

    Fantastic, one thing though instead of Regular expression to test the date in ASP you could use isDate(sVal) tis very nice though

  21. Dave Gregory · 5 years ago

    Great form! Thanks. I am having one problem. Once the form has validated correctly via php, it wont redirect for me. Very strange.
    I have put echos around my redirect and still nothing.
    ie.. echo “before redirect”; header(‘location:thanks.php’); echo “after redirect”;

    I get both echos, no redirect. not sure why.

  22. Chris Campbell · 5 years ago

    Dave, I’m on vacation right now so sorry to have missed your comment. The feedback is much appreciated. I actually ran into that problem awhile ago and will take a look at it when I get back. With the asp demo it works fine so I can’t see where the problem might be located. Please let me know if you happen to figure out what went wrong.

  23. Matthew Pennell · 5 years ago

    Finally got around to implementing this on a site I’m building - excellent work; just got a few comments/feedback.

    The validateMe() function doesn’t currently allow for the inputs having any class names before the ones related to the validation - might be worth adding that caveat into the implementation instructions?

    Also the validate() function is useless for anyone not using tables to layout their form - it could be improved by passing the element the author is using (span, in my case) as an argument of the function, and then calling document.getElementById(‘myFormName).getElementsByTagName(myElement).

    Finally, the biggest problem is that the validate() function checks through all the td’s for any with a className = “rules”… but they are never set anywhere else!

    To fix this, just add document.getElementById(gShow).className = “rules”; to the end of the handleHttpResponse() function.

    Apart from that, great work and really simple to use.

  24. Matthew Pennell · 5 years ago

    Oopsie - just noticed that your example code has the rules class already in the td tags. :o

    I think my version is better though, as they’re not needed unless Javascript is enabled so it makes sense to add them in using JS - unless they were going to be used by the ASP/PHP version when passing back a fail; perhaps a useful extension to the functionality?

  25. Matthew Pennell · 5 years ago

    Sorry to keep spamming these comments, but also - but shouldn’t the attachFormHandlers() function make a check for ‘validate’ being in the className? My page is throwing errors because I haven’t set all the input fields up to be validated (mainly because I don’t want to!)

  26. Chris Campbell · 5 years ago

    Spam away, Matthew, spam away. All great suggestions, and I’ll be sure to implement the check for validate before attachFormHandlers() and problem with inputs having more class names. Like I said to Dave, I’ll take a look after returning from vacation. I just can’t get the brain fired up here at beautiful Myrtle Beach, S.C.

  27. Matthew Pennell · 5 years ago

    Lucky guy. ;)

    I’ve actually completely re-written much of it to replace the ‘class name as validation list’ idea with ‘field name as validation list’ instead - I’ll publish it when I have some spare time to write it all up.

  28. Steven · 5 years ago

    When you just click the submit button, instead of tabbing through, or clicking outside the input, the onblur event isn’t called. Sounds like a tiny problem, but is confusing that javascript can through up errors, even if a field has valid data, just has not had onblur called.

    Anyone have a solution to this??

  29. Chris Campbell · 5 years ago

    If the data is automatically populated, you could first validate onload.

  30. Steven · 5 years ago

    Thanks for the reply Chris, good idea, but it’s not automatic. I just think that its quite common for people to finish filling out the last input, and then just click submit, rather than tabbing out of the input, or clicking outside. If this happens, the js becomes a problem, instead of helping the user.

    I’ve tried using various combinations of onkeyDown/Up and onBlur/Change, both hardcoded & set via DOM, and although I’ve nearly got there, there are just too many inconsistencies.

    Ideally, onsubmit should validate the input, based on what the value is, not the required label. Or would revalidate onsubmit. Any thoughts?

  31. Steven · 5 years ago

    I’ve come up with;

    objInput[iCounter].onblur = function(){return validateMe(this);} //attach onblur to each input field

    objInput[iCounter].onkeyup = objInput[iCounter].onblur; // set on keyup to onblur

    Which kind of solves my problem above. Its working for me, Windows XP, Firefox 1.04, IE6, IE55, IE5. No doubt there will be some inconsistencies elsewhere!

  32. Chris Campbell · 5 years ago

    Hmm maybe I’m not completely understanding you Stephen. On the demo, if I fill in the first two required fields but enter an invalid email address and press submit before tabbing, the error message fires. Right now, I’m only looking at it in IE 6 and Firefox if the problem is happening in a different browser.

  33. Steven · 5 years ago

    If you play around & enter some invalid data, the javascript will only pick up changes if the input loses focus. This does not happen if you just click the submit button, so valid data can be javascript invalid & vice versa, hence the .js becomes a problem.

    Sorry if not explaining properly!

  34. Kemar · 5 years ago

    Hey Chris or any. I am very new to this kind of stuff the Ajax and Php. In your example how would you send send or direct the email to you? Thanks ahead. Could you show me. Thanks.

  35. Ryan Campbell · 5 years ago

    We are actually heading out of town today, so don’t have time to put your request together. You can find good documentation over at the php site. I used this link to get started with email. Hope that helps.

  36. Aaron Heimlich · 5 years ago

    Interesting script, but from my understanding you are hitting the server every time the user moves from one form field to another. I thought one of the major benefits of client-side form validation was that it decreased the number of server hits that happen while the user is attempting to complete the form. Your script seems like it’s doing the opposite.

  37. Chris Campbell · 5 years ago

    You’re right, Aaron. It does hit the server every time and that could definatly be a downfall. I’ve used this on some forms which are not heavily used and there are no problems. If anybody uses this, it would be wise to do some testing beforehand.

  38. rich · 5 years ago

    I’m having a consistent problem with corrections. For instance say I enter the email addres wrong and the AJAX script informs me there is a problem - fine, i go back and alter it then hit submit. Because I havn’t tabbed to submit but just clicked it while the focus remains on the email text input it’s still assuming the email is wrong as no trigger has occured to make it recheck.

    Admittedly I’ve hacked around with this script to allow a textarea so i can use the validation with a ‘Contact Me’ form but I’m pretty sure there’s no function to check the validity of corrected fields which retain focus onSubmit

    Did that make sense? If not I can email you the URL of my test environment. Would appreciate your thoughts :-)

  39. rich · 5 years ago

    i think the key to the problem is validation of the form elements takes place onBlur. Clicking the Submit button (in latest version of Safari at least) doesn’t seem to register the onBlur from the previous highlighted element so no re-validation occurs.

  40. Nick Dunn · 5 years ago

    I’ve just written my own version which does almost exactly the same thing, without realising this article even existed! Bugger.

    But if anyone’s ever interested:

  41. analyzer x · 5 years ago

    This is a VERY nice script! :)

    one bug though…

    kills the error messages! :)

  42. Guy Thomas · 5 years ago

    I’ve developed a framework for PHP which I’m calling PLAJAX (pronounced PLAYJAX). It makes degradable validation easier to set up. Also it uses its own functions to make validation rules and warnings easier. E.g. ’ [#fld]==”” ’ will check the current field to see if it is empty instead of having to create the same validation over and over again. If you are interested in this project, please check Guy

  43. Audrey Berns · 5 years ago

    This looks great. (I am still digesting) I am wondering, can you provide the code to validate radio buttons and check boxes as well? Or does it not matter? Thanks! Audrey

  44. Brian Cairns · 5 years ago

    Everyone needs a hug.

  45. asdsa · 5 years ago

    Everyone needs a hug.

  46. Dan · 5 years ago

    I’m not sure how much this is looked at anymore, but I have a question when using images to let the user know if they have input information correctly.

    Basically the html is not rendered. I have an image, , that is displayed before the user inputs anything and would like it to change to when they get the right info in.

    I change the info in formvalidation.php from regular text to echo “”;. However on screen it reads as and no image is rendered. Maybe someone can help me. Thanks.

  47. Dan · 5 years ago

    Aww crud, I forgot that this comment block renders html tags.

    So all of those places where there looks like nothing is said, it is supposed to be <img src=…> and whatnot….I’m sure you can get the gist of it.

  48. DesignStage.Net · 5 years ago

    Interesting article

  49. Audrey Berns · 5 years ago


    Is it possible to use this method for the following?

    select/option lists radio buttons check boxes ?

    I have a long form and must make sure that various of the above form elements have a value other than 0. I don’t know enough (o.k. anything) about AJAX to try and expand your helpful code.

    Thanks. Audrey

  50. Applier · 5 years ago

    Having the following javascript error “Error: ‘document.getElementById(gShow)’ is null or not an object” while trying to submit the form.

  51. MPack · 5 years ago

    This is awesome, the exact behavior I was wanting for a new UI I’m working on. I’m trying to combine this though with an existing input class and function associated with onblur and am running into problems.

    I tried stringing the functions together, I’m getting the behavior but the validation breaks.

    Any ideas on combining this input.onblur with an additional class/function?


  52. Justin · 5 years ago

    This is a response to those asking about checking different types of tag names (select, input, etc).

    In the example, the author is using this code to attach the onBlur event to all the input elements to be validated :

    function attachFormHandlers() function attachFormHandlers() { // Ensure we’re on a newer browser if (document.getElementsByTagName) { gRequired = document.getElementById(‘required’).value; //get all required fields gAdditional = document.getElementById(‘additional’).value; // get all additional fields

        var objInput = document.getElementsByTagName('input'); // get all input tags
        var form = document.getElementById('form1') // get the form        for (var iCounter=0; iCounterThis is a response to those asking about checking different types of tag names (select, input, etc).  

    In the example, the author is using this code to attach the onBlur event to all the input elements to be validated :

    function attachFormHandlers() function attachFormHandlers() { // Ensure we’re on a newer browser if (document.getElementsByTagName) { gRequired = document.getElementById(‘required’).value; //get all required fields gAdditional = document.getElementById(‘additional’).value; // get all additional fields

        var objInput = document.getElementsByTagName('input'); // get all input tags
        var form = document.getElementById('form1') // get the form        for (var iCounter=0; iCounter
  53. pappu singh · 4 years ago

    excellent. its so simple so that freshers can understand easily.

  54. fghdfhfgd · 4 years ago

    Everyone needs a hug.

  55. Ben Wann · 4 years ago

    Thanks for a great article, just one note, your link to unobtrusive javascript is broken…..

    Looks like your internal linking is a bit off.. You have: When I think you want:

    Hope this helps, I wanted to know it so much I tracked it down! Thanks for bringing all of this together!

  56. puiu · 4 years ago

    Everyone needs a hug.

  57. r · 4 years ago


    i think this script is pretty good, however how would i modify this in order to make an email contact form?

    i don’t have any prior programming knowledge so any help would be greatly appreciated!

    thanks for reading!

  58. Merlin · 4 years ago


    excellent script. I am also wondering how to use images instead of text. Dan has already commented on that before. Any idea on how to achieve this?



  59. Alec · 4 years ago

    FOR THOSE LOOKING TO USE IMAGES: See this post in the Google Groups: Professional PHP Developers - I was wondering the same thing, so I posted there and here it is:

  60. samir amrutya · 4 years ago

    Everyone needs a hug.

  61. dd · 4 years ago

    Everyone needs a hug.

  62. Wasim · 4 years ago

    Hi thanks for the example. Do you have one for ASP.NET?

  63. mshonich · 4 years ago

    That’s stupid. JavaScript checks are done in order to skip the round-trip to server because it is way slower, no matter whether you are using AJAX or simple good`ld POST.

    I’ve always thought that ASP developers have the option of writting some smart script tags with runat=’server’ to run the same set of JavaScript checks both at the server and the client.

    That’s PHP and Perl failure - different languages at client and server side will always require code duplication.

    Have you understood what original is about?

    It speaks exactly the following: if you had simple Regexp based checking, then you can generate proper JavaScript validation routines automatically with same one PHP code that is used to generate the form. I think you should use that technique to speed up majority of your’ currently sloopy AJAX-server-backed checks.

  64. Ryan Campbell · 4 years ago

    Speed is not the concern with this tutorial. While the code is out dated and somewhat sloppy (this was written over a year ago!), the point is that JavaScript can be easily hacked, so it can’t be used as a validation method. Also, maintaining two codesets (one client, one server) leads to confusion, even if the JavaScript side is pregenerated for you. So, the benefit to using Ajax is not for the speed, but so that you can give your users live feedback about the form without having to maintain two codesets. And if no JavaScript is enabled, everything works fine still.

  65. Chris J · 4 years ago

    Great script, very good introduction to the Ajax phoenomenon!

    However, i noticed that if the form you are validating is pre-populated - eg Great script, very good introduction to the Ajax phoenomenon!

    However, i noticed that if the form you are validating is pre-populated - eg

  66. Chris J · 4 years ago

    My comment above got truncated because of my example:

    Great script, very good introduction to the Ajax phoenomenon!

    However, i noticed that if the form you are validating is pre-populatedusing the value attribute, the validation state of each element is initialised incorrectly. is there an easy way to do an initial check of the form the first time it is rendered, and correct all of the message labels?

    Also, someone mentioned that this method is outdated, and that better scripts now exist (a year or so later) im curious to see how this can be improved, so any links would be great…

  67. John Best · 4 years ago

    This script works fine on my local testing server (Windows with Apache), but fails when I try it on a remote server running Linux. Using the sample form provided (index.php), the email address fails to validate. “Required” turns red and the form does not submit, even though a valid email address was entered. The same version of PHP is running on both the local and remote. Any idea what the problem could be?

  68. gui · 4 years ago

    AWESOME… thanks for this…

  69. gui · 4 years ago

    I cannot get this sucker to work for me… I have tried everything… if someone could shoot me an email and tell me what I am doing wrong… I am a PHP guy, and I kinda limp through the Javascript… if anyone could help me out that would be much appreciated!!!! PLEASE!!!

  70. Bela Black · 4 years ago

    Awesome info - helped out a lot - thanks.

  71. boy · 4 years ago


  72. Kumar Chetan · 4 years ago

    clicking on change to php /asp gives error, see this “changeLanguage is not defined”

  73. krihsna · 4 years ago

    Everyone needs a hug.

  74. Tera Patrick Fucking · 4 years ago

    Tera Patrick Fucking

  75. mark · 4 years ago

    Does anyone have any URLs demonstrating this. I am a product manager and interested in seeing the implementation, more than the code snippets.

    Thanks, Mark

  76. Darkelve · 4 years ago


    can someone please tell me how I can make this work with a text area object instead of an input field? (just to check if anything is entered in the field)

    Oh and thanks for the great script! And double thanks for both posting it in ASP and PHP! :)


  77. Lee · 4 years ago


    Email me at and I will send you a link with it implimented.


  78. ajaxlines · 4 years ago

    Thanks for this article

    ajaxlines webmaster

  79. asdsd · 4 years ago

    Everyone needs a hug.

  80. everyone · 4 years ago

    Everyone needs a hug.

  81. vnvnv · 4 years ago

    Everyone needs a hug.

  82. deepthi · 4 years ago

    Everyone needs a hug.

  83. Alex · 4 years ago

    Thank You

  84. sasi · 4 years ago

    Everyone needs a hug.

  85. decg · 4 years ago

    Everyone needs a hug.

  86. burçlar · 4 years ago

    thank you good.


  87. Adeline · 4 years ago

    i need a hug

  88. Josh · 3 years ago

    I want to give you a hug

  89. Dev · 3 years ago

    hello, first of all great script. i’ll get straight to the point, i’m new to ajax, js my problem is that i’m using css to layout my form and am not sure how i can edit the validate() code to work with the css form. Is there any chance you could give an example of how i can change this piece of code to work with css form.

    I’ve read through comments and someone called “Matthew Pennell” has explained it but like i said i’m a newbie to ajax/js and dont really understand it much …

    i hope you could help me out.

    Thank you

  90. anthony · 3 years ago

    Great script, thanks. I’ve got the validation working well with the ASP version.

    My only problem is that I can’t seem to get it to work with my form to email component (ASPMAIL). The form is being process my ASPMAIL and I am getting the resulting email. The problem is that the email is blank.

    Can anyone help?



  91. Shannon Cronin · 3 years ago

    This is a great tutorial. My one question is, how would I replace the “Required” and “Thank You” text with two separate images instead? I have tried changing the code in the formvalidation.php file to:

    if (ereg (“^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$”, $val, $regs)) { echo “”; } else { //other code }

    Yet when it actually gets to the browser it just echos the path and not the image. Is this because of the validate.js file? Thanks.

  92. asdf · 3 years ago

    Everyone needs a hug.

  93. Mike · 3 years ago

    A good complement to this for automatically handling all the tough work is AJForm.

  94. Timon Bergen · 3 years ago

    Everyone needs a hug. I agree.

  95. Jon · 3 years ago

    Everyone needs a hug. <- I hug you.

    Tree Huggers

  96. Yettie · 3 years ago

    Everyone needs a hug. I need a mug!