Ajax Form Validation - sForm

There are a several AJAX applications for form validation, like the one from Particletree, from roscripts, dustindiaz, dexagogo, fValidate, or FormAssembly. All these scripts are really great, but I didn’t found something that’s really simple, e.g. without using any AJAX library, so I decided to code one myself.

You can see it in action here. To download it, please go to the bottom of this article.

Introduction

Our goal is to provide a real-time feedback for our users, when they are reading and filling our form.This needs to be really simple, so that even the dummiest user is able to recognize, that something is going wrong. To do this, we have to use some colors (in my opinion), to let the users know what’s happening, that means, that the incorrect fields are going to be red after validation and the correct fields will turn green. We will add after each validation after the field an image, too, to express by visualization the fields correctness.

Why is that good for the user? Because using newest technology, AJAX, we are able to give him real-time server-side validation. The user doesn’t has to refresh each time he’s correcting an incorrect field in order to get feedback. On large forms with several fields this is really annoying.

How it works

First, let’s have a look at a few screenshots, and then later the code. I’m a visual person, so I always look at the screenshots, if there are any. Loading it the first time, it’ll look like this:

1st

If all fields are filled like they have to be, they will turn into a green color, letting the user know, that it’s OK. I’ve written some examples on the right side in light-grey, because I think, that you have to give the user a clue how to fill the field. Read this article about mistakes by designing a form, it’s about login forms but I think it’s worth to read it. However, our form with correctly filled fields will look like this:

2nd

Let’s have a look, how it’ll behave when the user’s misstyping something, like the date:

3rd

Even if he fills all other fields correctly, the submit button is disabled, ’til all fields are correct:

4th

The JavaScript:

The JavaScript attaches first to all input elements an onblur with the getForm() function, this will pass the data to the PHP script once the particular field isn’t focused anymore. We have to add the type of our validation and whether it’s required or not to each input elements class name (you can see a description in the HTML section) separated by comma. However, when validation is done, the server gives a response whether the input elements value is correct or not according to the regular expression. If you want to add an input element to your form, that isn’t required, you can still validate it putting only the type into its class. If it’s empty, the server will give us a “none” as response and it won’t be validated, but if there’s something written inside the field, it still has to be valid. Validation is done client-side with the validateIt() function.

There are three possible responses from the server: true, false and none.

true we will get, if the particular field is required and the value of it is correct after validation OR if the field isn’t required but it does have a value and the value is correct after validation

false we will get, if the particular field is required and the value of it is incorrect after validation OR if the field isn’t required but it does have a value and the value is incorrect after validation

none we will get, if the particular field isn’t required and it hasn’t got a value

The server-side response of the validation is handled by the handleHttpResponse() function, which will do the coloring of the input element and puts an image after it. It will disable the submit button if one of the fields is incorrectly filled and re-enable it if all of the fields are correct (ehm, sometimes this doesn’t work very well, please check it). Let’s see the code:

// Load the getForm function while page is loading
window.onload = getForm;
 
// Set this to your validation PHP script, default is "validate.php?value="
var vUrl = "validate.php?value=";
 
// Set this to your form's id
var formid = "vform";
 
// This is the array for error handling
var vError =  [];
 
// We attach to every input field a little js
function getForm() {
 
	// Important: Our form has to got the "vform" id
	var form = document.getElementById(formid);
 
	if (document.getElementsByTagName) {
		var vInput = document.getElementsByTagName("input");
		for (var vCount=0; vCount<vInput.length; vCount++)
			vInput[vCount].onblur = function() { return validateIt(this); }
	}
}
 
// Refers to the function
http = getHTTPObject();
 
function getHTTPObject() {
 
  var xmlhttp;
 
  /*@cc_on
 
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
      try{
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }catch(E){
      xmlhttp = false;
    }
  }
  @else
    xmlhttp = false;
  @end @*/
 
  if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
    try {
      xmlhttp = new XMLHttpRequest();
    }catch(e){
      xmlhttp = false;
    }
  }
 
  return xmlhttp;
 
}
 
// The main validation-function
function validateIt(vInput) {
 
	// Each input field's id
	vId = vInput.id;
	vValue = vInput.value;
 
	// Separate the class attr of each input field
	getValue = vInput.className;
	if(getValue.indexOf(",") == -1 ) {
		vType = getValue;
		vRequired = "";
	} else {
		vRules = vInput.className.split(",");
		vRequired = vRules[0];
		vType = vRules[1];
	}
 
	// The whole URL
	var url = vUrl + (vValue) + "&required=" + (vRequired) + "&type=" + (vType);
 
	// And finally we send it to the url we specified
	http.open("GET", url, true);
 
	// The handleHttpResponse is the function we call, when we have an
	// answer back from the PHP script
	http.onreadystatechange = handleHttpResponse;
	http.send(null);
 
}
 
// A function to handle the response from the PHP script
function handleHttpResponse() {
 
	if(http.readyState == 4) {
 
		// Refering to the PHP script, for every validation we'll get
		// either true or false and apply some visual changes in order to
		// get the user focusing on each field whether it's ok or not
		// If one of the input fields contains an error, the submit button
		// will be disabled, until the error (that means all errors) are
		// solved
		if(http.responseText == "false") {
 
			var sInput = document.getElementById(vId);
			var vButton = document.getElementById("submit");
 
			document[vId].src = "img/false.png";
			sInput.style.border = "1px solid #d12f19";
			sInput.style.background = "#f7cbc2";
			vButton.disabled = true;
			vError.push(vId);
 
		}
 
		if(http.responseText == "true") {
 
			var sInput = document.getElementById(vId);
 
			document[vId].src = "img/true.png";
			sInput.style.border = "1px solid #338800";
			sInput.style.background = "#c7f7be";
 
			// We do a check if our element is in the error array, and if
			// so, we can delete it from the array
			if(vError.indexOf(vId) != -1) {
				var aId = vError.indexOf(vId);
				vError.splice(aId, 1);
				if(vError.length > 0) {
					var vButton = document.getElementById("submit");
					vButton.disabled = true;
				} else {
					var vButton = document.getElementById("submit");
					vButton.disabled = false;
				}
			}
		}
 
		if(http.responseText == "none") {
 
			var sInput = document.getElementById(vId);
			var vButton = document.getElementById("submit");
 
			document[vId].src = "img/blank.gif";
			sInput.style.border = "1px solid #aaa";
			sInput.style.background = "#ffffff";
			vButton.disabled = false;
 
		}
 
	}
}

I’m new to JavaScript and AJAX, so I still have some issues that I can’t figure out. In JavaScript the array-handling is a little bit confusing for me and it doesn’t work like I want it to. If a field isn’t filled correctly, the submit button will be disabled until the current field is corrected. This is done by adding every input field’s id to the error array that isn’t correctly filled respectively to delete every input field’s id from the array that was incorrect but was corrected meanwhile. Maybe somebody who’s better than me in JS coding will be able to help me with this issue :P

The PHP:

Using the GET method, we’ll pass all of our variables to the validation PHP-script. This will look like this:

validate.php?value=fieldsvalue&required=required&type=email

In order to check all of these variables, we have to use some regular expressions. Of course you can add your own validation types using the Regular expression library.

We have to check first if a field is required or not. If it’s required but it’s empty, we have to return false. Then we check the type of the variable and use regular expressions to check if it’s correct. You can use following validation types:

  • alpha
  • alphanum
  • date
  • email
  • number
  • url
<?
/*
 * This is the PHP script to validate the form over AJAX
 * Validations possible:
 * - number
 * - alpha
 * - alphanum
 * - date
 * - email
 *
 */
 
// Start the main function
StartValidate();
 
function StartValidate() {
 
    // Assign some var's for the requests
    $required = $_GET["required"];
    $type = $_GET["type"];
    $value = $_GET["value"];
 
    // This is the function to check if a field is even required or not
    // So it's useful if you only want to check if it isn't empty
    validateRequired($required, $value, $type);
 
    switch ($type) {
        case 'number':
            validateNumber($value);
            break;
        case 'alphanum':
            validateAlphanum($value);
            break;
        case 'alpha':
            validateAlpha($value);
            break;
        case 'date':
            validateDate($value);
            break;
        case 'email':
            validateEmail($value);
            break;
        case 'url':
            validateUrl($value);
            break;
    }
}
 
// The function to check if a field is required or not
function validateRequired($required, $value, $type) {
    if($required == "required") {
 
        // Check if we got an empty value
        if($value == "") {
            echo "false";
            exit();
        }
    } else {
        if($value == "") {
            echo "none";
            exit();
        }
    }
}
 
// There are regular expressions in order to check a fields input, you can
// get most of them at the Regular expression Library at http://www.regexlib.com
// There you can check your own regular expressions, too
 
// Validation of an Email Address
function validateEmail($value) {
    if(ereg("^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$", $value, $regs)) {
        echo "true";
    } else {
        echo "false";
    }
}
 
// Validation of a date
function validateDate($value) {
    if(ereg("^(([1-9])|(0[1-9])|(1[0-2]))\/(([0-9])|([0-2][0-9])|(3[0-1]))\/(([0-9][0-9])|([1-2][0,9][0-9][0-9]))$", $value, $regs)) {
        echo "true";
    } else {
        echo "false";
    }
}
 
// Validation of an URL
function validateUrl($value) {
    if(ereg("^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$", $value, $regs)) {
        echo "true";
    } else {
        echo "false";
    }
}
 
// Validation of characters
function validateAlpha($value) {
    if(ereg("^[a-zA-Z]+$", $value, $regs)) {
        echo "true";
    } else {
        echo "false";
    }
}
 
// Validation of characters and numbers
function validateAlphanum($value) {
    if(ereg("^[a-zA-Z0-9]+$", $value, $regs)) {
        echo "true";
    } else {
        echo "false";
    }
}
 
// Validation of numbers
function validateNumber($value) {
    if(ereg("^[0-9]+$", $value, $regs)) {
        echo "true";
    } else {
        echo "false";
    }
}
 
?>

The HTML:

The HTML is really easy, you just have to include the javascript file, the CSS styles file and write your form. Remember to put some validation-information to each input elements class name. If it’s required and the type is email it’ll look like this: class=”required,email”, if it isn’t required but you still want to validate it with type email it’ll look like this: class=”email” (without comma). If your form has another id than “vform” please do not forget to edit the validate.js JavaScript file. Of course you can delete the line with the example, it’s only for the users comfort.

<html>
<head>
 <title>sForm - Simple Ajax Form Validation</title>
 <script src="validate.js" type="text/javascript"></script>
 <link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>
 
<body>
 
<form name="vform" id="vform" method="get" action="test.php">
 
 <label for="email">Email: </label>
 <input type="text" name="email" id="email" class="email" autocomplete="off">&nbsp;
 	<img width="16" height="16" name="email" src="img/blank.gif" alt="">
	<span class="expl">email address, like user@domain.com</span>
 <br />
 
 <label for="date">Date: </label>
 
 <input type="text" name="date" id="date" class="required,date" autocomplete="off">&nbsp;
 	<img width="16" height="16" name="date" src="img/blank.gif" alt="">
	<span class="expl">only date (mm/dd/yyyy), like 01/31/2008</span>
 <br />
 
 <label for="number">Number: </label>
 <input type="text" name="number" id="number" class="required,number" autocomplete="off">&nbsp;
 	<img width="16" height="16" name="number" src="img/blank.gif" alt="">
	<span class="expl">only numbers, like 1234</span>
 <br />
 
 <label for="alpha">Alpha: </label>
 <input type="text" name="alpha" id="alpha" class="required,alpha" autocomplete="off">&nbsp;
 	<img width="16" height="16" name="alpha" src="img/blank.gif" alt="">
	<span class="expl">only characters, like abcd</span>
 <br />
 
 <label for="alphanum">Alphanum: </label>
 <input type="text" name="alphanum" id="alphanum" class="required,alphanum" autocomplete="off">&nbsp;
 	<img width="16" height="16" name="alphanum" src="img/blank.gif" alt="">
	<span class="expl">numbers and/or characters, like 123abc</span>
 <br />
 
 <br />
 
 <input type="submit" name="submit" id="submit" value="Submit">
 
</form>
</body>
</html>

The CSS:

If you want to apply your own style, please have a look at the validate.js, too, where you can modify the validation colors in the handleHttpResponse() section. Please note that if you want to validate a field, that isn’t required and the user doesn’t fill it, you’ll get a “none” response back from the server applying the old style of the input field (this has to be done, because of the following scenario: the user fills information in this field, it will be validated and colored, but after this maybe the user is changing his mind and deletes the value of the field, then the empty field has to get back his standard colors), so please change the style of the “none”-response, too, if you change it in your CSS, until I’ll find a better solution for this :)

I made some tests of the CSS under:

  • Internet Explorer 7
  • Firefox 2.0.0.11

So I’m sure this needs to be hacked to work in IE6, IE5, Opera, Konqueror and so on… If you need it to work on those browsers, just let me know, leave a comment or send me a message.

form, br {
	clear: left;
	margin: 0;
	padding: 0;
}
 
label, input {
	width: 140px;
	float: left;
	font: 11px bold Tahoma, Arial, sans-serif;
	margin: 1px;
	padding: 2px;
}
 
label {
	font: 14px bold Tahoma, Arial, sans-serif;
	background: #eeeeee;
}
 
.expl {
	color: #888;
	font: 10px normal Tahoma, Arial, sans-serif;
	font-style: italic;
}

Any comments, feedbacks or reports are welcome.

See it in action, or

download it:

Related posts

1 Star2 Stars3 Stars4 Stars5 Stars (12 votes, average: 4.25 out of 5)
Loading ... Loading ...

20 Responses

  1. You are the best man :D

    mr F on January 26, 2008 at 22:19
  2. I finally decided to give you a little feedback ! well you got it! i love your site !!! no , really, its good…

    book makers on January 29, 2008 at 1:00
  3. Na, akkor feedback…
    A ZIP file tartalmazza a tgz-t is :)
    A zip file img könyvtára üres :( a tgzből kellett a képeket visszavadászni.
    Kibővíthető lenne azzal, hogy a Submit mező default disabled, és csak akkor enabled, ha az ÖSSZES required field helyes.
    Illetve ha van két jelszó mező, akkor azt is ellenőrizhetné, hogy azok azonosak-e.
    Amúgy a script maga nagyon jó!
    Csak így tovább

    bandy on February 1, 2008 at 15:06
  4. kosz bandy :)
    kijavitottam a letoltheto fileokat es ezennel ellenoriztem is.

    a scriptet meg az altalad javasolt funkciokkal nem bovitettem, de amint lesz idom es erom ra, megcsinalom es szolok az ujitasokrol.

    István on February 1, 2008 at 21:31
  5. Hi! I’m John Strass and i like your site!
    Thank you!

    John on February 2, 2008 at 14:33
  6. There was a small problem , i think the submit button should be disabled if the fields are empty , but this is not the case here :(

    Tarek on February 4, 2008 at 11:52
  7. Issue solved by adding those two lines after the getForm function :
    var form = document.getElementById(formid);
    var vButton = document.getElementById(”submit”);

    so now the submit button is disabled if there are no data on the field :)

    anyway , the function you have written is So great and easy to use .

    i will digg it :)

    thanks .

    Tarek on February 4, 2008 at 13:49
  8. After some checks , i found this form doesn’t work on IE6 as you have said , now , what’s Next ?
    i need the hacks please …

    Tarek on February 5, 2008 at 9:27
  9. Is there anyway to use the different validations more then one time in one form? It doesn’t work if I assign for example alpha to two different fields.

    Any idea what I should adjust?

    Darice de Cuba on February 6, 2008 at 15:11
  10. that is great but can you add a button to display a calendar to check a date

    junior on February 6, 2008 at 18:46
  11. Great job. But it would be even better if someone find solution to make it work under IE6 and Opera.

    Sorry for my English and Thank you :)

    Minsc on February 6, 2008 at 21:04
  12. where is test.php?

    oasis on February 13, 2008 at 10:52
  13. This code is really useful and suit with my need. I need to develop feedback page on the website using ajax to validate the form. But some methods used by the code doesn’t support by IE and somehow error happens when i try to back and forth from email to alphanum and alphanum to email then the summit button doesn’t enabled.

    Ratha on February 15, 2008 at 3:52
  14. Well I thing I just find the reason why it does’t work in IE5,6 and Opera. These browsers don’t support the array propertie indexOf, but there is a cure on this site under section Compatibility:
    http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:indexOf

    I tried it and it works very well :)

    I hope this will help u.

    Minsc on February 16, 2008 at 12:32
  15. The IndexOf fix for IE works fine ! i am only stuck with the button staying disabled when i switch from alphanum to email and back some body got a fix for this ?

    webdesign on March 28, 2008 at 11:38
  16. quite good and clean design with complete source

    Thx a lot mate =)

    newsoulhk on March 29, 2008 at 15:24
  17. i.explorer 7 error submit button is not active when all cell’s ok. Say’s like object not supported this methode

    James Crew on April 2, 2008 at 12:23
  18. RULES :)

    This on May 17, 2008 at 1:39
  19. i would like to know that how i should validate a form so that i can whole comment on see on submit button.

    Jagat Pal Maurya on May 20, 2008 at 13:03
  20. Great script!

    I have only a problem with a form field for a full name which includes a white space.

    Rudy on June 5, 2008 at 21:31

Zahnarzt Ungarn, Zahnbehandlung Ungarn : Zahnimplantat Ungarn, Zahnimplantate Ungarn : Zahnersatz Ungarn