View Full Version : Live form validation!

05-17-2007, 10:21 PM
Hi, before you say look on google i have.

What i am trying to do is i have a form on my website and i want when the user clicks out of the box it validates it in real time. So if its i valid put an image next to the field. And if its not then put a different image next to it.

I usually only use PHP and not much JS i am sorry if this is a noobish question. I don't know.

Please help!

~ Christian

05-18-2007, 01:21 AM
Hello Christian,

I have created a small example to help you out.

Here it goes...just copy and paste into a new file ;)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
<meta http-equiv="content-language" content="en" />
<title>OnBlur Example</title>
<script type="text/javascript">
* checkMe expects
* a reference to table cell (well, any tag with a given id really)
* where the image will be displayed in case of success or error.
function checkMe( displayId) {
// create a pattern to match the email address
var email_pattern = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
// get a reference to the location where we want to display the image
var display_area = window.document.getElementById( displayId );
// get a reference to the form
var me_form = window.document.forms[0];
// get a reference to the text field
var email = me_form.email;
// validate if email input text field contains an email or not
if( email.value.match( email_pattern) ) {
display_area.innerHTML = "Thanks, email format was accepted. :)";
} else {
display_area.innerHTML = "Sorry, but text supplied does not validate as an email address";
} //-- ends else
} //-- ends function checkMe
<form method="get" action="#">
Your Email:
<input type="text" name="email" size="35" onfocus="javascript: window.document.getElementById('display_area').innerHTML='Checking....';" onblur="javascript: checkMe('display_area');"/>
<td id="display_area">