Using Inline Form Validation

By Eddie Machaalani

Introduction

Javascript alert boxes have long been used for validating HTML forms. For example, if you forget to type your name into a contact form, then a Javascript alert pops up telling you about your error and how to correct it. While this is a lot better than no warning message or validation at all, I find alert messages quite annoying, ugly and outdated.

What I'd like to do in this article, is show you a more elegant way of displaying error messages cleanly, using some easy to implement Javascript. This not only makes your forms a lot cleaner and more usable, but also shows your attention to detail as a web designer.

The Finished Product

Here’s what the finished product will look like. Notice the error message is displayed in red on the form itself:


A Simple Form

First, we start with a simple form. I’ve kept it basic on purpose so that you can easily modify or add to it if the need arises.

Below we have a basic contact form that collects a visitors name, email address and comments.
Note that this article doesn’t discuss the server-side code needed to actually capture and send the form, but rather it discussed the client-side validation of the form data.

<form method=post action="myscript.php">
<span class=label>Name:</span><input type=text value=""><br>
<span class=label>Email:</span><input type=text value="" id=email><br>
<span class=label>Comment:</span>
<textarea type=text value=""></textarea><br>
<input type=submit value=Submit style="margin-left: 50px">
</form>


There's nothing special about this form. I've used some <span> tags for spacing and formatting purposes (In the CSS code which I'll show you later).

Attaching ID’s to Form Elements

What we need to do now is simply attach ID's to each form element. An ID is a unique name we give to each form element, which Javascript can use to identify every form element separately so that it can retrieve it's value and properties.

For example:
<span class=label>Name:</span><input type=text value="" id=name ><br>

Adding Error Messages

The error messages are simply <div> tags that have been hidden using the CSS attribute, display:none. So essentially, these <div> tags will be loaded but hidden. However, when we find that a form field is empty, we will show the hidden <div>, which will contain an error message:

<form method=post action="myscript.php">
<span class=label>Name:</span>
<input type=text value="" id=name><br>
<div class=error id=nameError>Required: Please enter your name<br></div> <br>
<span class=label>Email:</span><input type=text value="" id=email><br>
<div class=error id=emailError>Required: Please enter your email address<br></div> <br>
<span class=label>Comment:</span><textarea type=text value="" id=comment></textarea><br>
<div class=error id=commentError>Required: Please enter a comment<br></div> <br>
<input type=submit value=Submit style="margin-left: 50px">
</form>


Javascript Validation

Now, on to the Javascript that validates the form objects. For the sake of clarity, I'll only describe code for one form element, the Name field. You can get the entire source code at the end of this article.

Firstly, we need to call the Javascript checkForm function when we post the form:
<form onSubmit="return checkForm();" method=post action="myscript.php">

By using a return attribute, if the validation of the form fails, the form will not be submitted. If the validation returns true, however, then the form will be submitted as normal.

The checkForm function checks to make sure that all required form fields are complete. If not, we display an error message next to the corresponding field and set the focus of the cursor back into the form field with the error:
function checkForm() {
name = document.getElementById("name").value;
if (name == "") { document.getElementById("nameError").style.display = "inline";
document.getElementById("name").select();
document.getElementById("name").focus();
  return false;
  }
  return true;
}


When adding the additional data validation, I've created a separate function to hide all other error messages so that we only see one error message at a time. This is critical so that you don't overwhelm your visitor with many error messages at once. This also simplifies the process of re-checking if data is actually correct.

Conclusion

And there you have it – easy form validation without any annoying Javascript alert messages. The complete source code is shown below, and as you can see, form validation doesn't necessarily have to be ugly and tedious:



<html>
<style>
  input {
  width: 200px;
  font-family: Tahoma;
  font-size: 8pt;
  }
 
  .label {
width:50px;
  }
 
  textarea {
width: 200px;
  font-family: Tahoma;
  font-size: 8pt;
  }
   
  body {
font-family: Tahoma;
  font-size: 8pt;
  }

  .error {
  font-family: Tahoma;
font-size: 8pt;
  color: red;
  margin-left: 50px;
  display:none;
  }
 
</style>
 
<script>
  function checkForm() {
name = document.getElementById("name").value;
  email = document.getElementById("email").value;
  comment = document.getElementById("comment").value;
 
  if (name == "") {
  hideAllErrors();
document.getElementById("nameError").style.display = "inline";
document.getElementById("name").select();
document.getElementById("name").focus();
  return false;
  } else if (email == "") {
hideAllErrors();
document.getElementById("emailError").style.display = "inline";
document.getElementById("email").select();
document.getElementById("email").focus();
  return false;
  } else if (comment == "") {
hideAllErrors();
document.getElementById("commentError").style.display = "inline";
document.getElementById("comment").select();
document.getElementById("comment").focus();
  return false;
  }
  return true;
  }
 
  function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("commentError").style.display = "none"
  }
</script>
 
<body>
<form onSubmit="return checkForm();" method=post action="myscript.php">
<span class=label>Name:</span><input type=text value="" id=name><br>
<div class=error id=nameError>Required: Please enter your name<br></div><br>
<span class=label>Email:</span><input type=text value="" id=email><br>
<div class=error id=emailError>Required: Please enter your email address<br></div><br>
<span class=label>Comment:</span><textarea type=text value="" id=comment></textarea><br>
<div class=error id=commentError>Required: Please enter a comment<br></div><br>
<input type=submit value=Submit style="margin-left: 50px">
</form>
</body>
</html>




40 Responses to "Using Inline Form Validation"

Fill in the form below to leave a comment and share your thoughts.

 
René Jansen
said this on 08 Jan 2006 12:34:12 PM CST
Hi Eddie, Thanks for the excellent explanation of inline form validation. Your article taught me just what i needed.


 
an unknown user
said this on 12 Jan 2006 5:37:24 AM CST
You guys are so smart! I am jealous!

 
Megan Richardson
said this on 01 Feb 2006 4:05:17 AM CST
Have been searching for the 'simple' answer all night - thanks for making it easy to understand.

 
Sam
said this on 27 Feb 2006 8:47:26 AM CST
That is so cool.
And all this time Ive been using alert boxes.
Never again

 
Dan
said this on 28 Feb 2006 8:19:36 PM CST
Very nice, thank you very much for explaining this clearly!

 
Charm
said this on 30 Apr 2006 10:14:07 PM CST
Brilliant! Thank you for the wonderful tutorial.

 
srinu
said this on 08 May 2006 3:23:55 AM CST
Very useful thank u very much

 
Byron
said this on 19 May 2006 9:24:37 AM CST
Very Nice, but what if Java is disabled? This is what I am looking for, but I want it all to be server-side based.

[Editors note] Hi Byron, it's very rare these days that JavaScript is disabled. I'd say it's enabled on 99% of PC's. If it is disabled you'd have to use a server-side validation technique.

 
JJ
said this on 23 May 2006 4:07:26 PM CST
Straight to the point. Thanks for the example!

 
Jo Adamson
said this on 05 Jun 2006 3:55:40 PM CST
Fantastic explanation that was ideal to solve my problem. Liked the step-by-step approach.
Great!

 
Philippe
said this on 19 Jun 2006 12:45:47 PM CST
I have been looking for something smart for a while and didn't find anything..... your script is great as so simple... it makes me flush to see how simple things can be..... when you are skilled.

Thanks again,
Philippe

 
Francesco
said this on 07 Jul 2006 8:39:05 AM CST
Nice, very Nice...simple, cleare and informative.

Well done

 
Sue Gerrey
said this on 13 Jul 2006 5:39:01 AM CST
Thanks so much for the script. I have looked everywhere for something like it and appreciate your sharing it.

 
Lena
said this on 26 Jul 2006 3:52:07 AM CST
Thank You for letting me leave the use of alert boxes behind.

 
Ajith Joseph
said this on 01 Aug 2006 10:53:04 PM CST
This was what I wanted

 
Radhab Shrestha
said this on 14 Aug 2006 1:30:30 PM CST
Very effective for the website verification. Thanks for the content it is useful for all.

 
hari
said this on 31 Aug 2006 8:20:29 AM CST
good stuff

 
Pal
said this on 31 Aug 2006 8:30:51 AM CST
very simple n useful. pls teach some more useful scripting..

 
Julean
said this on 03 Sep 2006 11:46:05 PM CST
I've have not seen a more elegant yet simple piece of script. So easy to modify.

Very nice work! A big thanks!!!

 
rakeshnagpure
said this on 29 Nov 2006 11:55:19 PM CST
Excellent work you have done.
I inspired and adoptted your coding.
thanks a lot my friend.

 
shridhar
said this on 20 Dec 2006 7:41:06 PM CST
Its what i was looking for and need of the hour thanx a lot

 
yahoozled
said this on 21 Dec 2006 11:48:34 AM CST
i can't tell you how great it was to come across this. i've been using complicated php-scripts on receiving end to validate and now i can move those rules back here and pre-validate.

thanks for being so bloody clear and such a simple example!

btw, if you add {font-family:Tahoma;font-size:8px;} you can eliminate alot of the repeated CSS.

 
gopi
said this on 23 Dec 2006 5:37:15 AM CST
simply Fantastic!

 
mathi
said this on 29 Dec 2006 11:27:16 AM CST
hi! your explanation realy good...keep on..

 
Erik
said this on 22 Jan 2007 5:05:51 AM CST
Dead On! This was short, concise, and to the point.
Excellent explaination and example.
I would love to see a similar walkthrough for radio buttons, but with a little sleep and this example, I'm sure I can figure it out.

Well Done!!

 
Debra W.
said this on 08 Mar 2007 12:40:02 PM CST
GREAT - thank you - and it teaches me about hidding and showing elements too

 
sam
said this on 03 Apr 2007 11:41:13 AM CST
Very good Example

 
mad(real initials)
said this on 16 Apr 2007 7:13:55 AM CST
God bless you. I have been trying to figure this out for a class. The prof keeps giving hints. We are allowed to find answers online. :-) I just didn't know the term "inline".

 
anthony
said this on 02 May 2007 3:20:08 PM CST
awesome, any easy way to validate the email for correct formatting; ie. a real email address?

 
Peter
said this on 13 Sep 2007 2:43:56 PM CST
Interesting, but what I am looking for is something that will validate fields as the user exits each one. onblur() I suppose... Any ideas on that?

 
Garrett
said this on 20 Sep 2007 10:19:11 PM CST
Digg it!

 
Cheese
said this on 30 Oct 2007 7:19:19 AM CST
Brilliant cheers!

 
shrilakshmi
said this on 07 Dec 2007 3:22:37 AM CST
It's really fantastic.It is explained in so simple way.This is what i wanted.Thank You

 
Daniel
said this on 16 Feb 2008 9:28:54 PM CST
Thank you for such clear explanation and for sharing this code. I am wondering how you would use this code with two forms on the same page.

 
jorgerosa
said this on 14 May 2008 1:36:27 PM CST
THANK YOU! Just what i needed.
And guess what: Simple clean code and works just like a dream! :D

 
Simon
said this on 04 Jun 2008 7:37:45 AM CST
Wow the simple answer I was looking for!!!!! :)

 
Simon
said this on 04 Jun 2008 7:39:15 AM CST
wow amazing ! what I was looking for!

 
Dudu
said this on 04 Jun 2008 11:09:05 AM CST
Muito bom!!! Very good!

 
Alex Jordan
said this on 11 Sep 2008 5:04:45 AM CST
Great script, I've been looking for this for a while. The only problem I've found is that I can't seem to get it to work in Firefox, it works perfectly in IE7 so I don't know what is wrong there. If you have any suggestions then I would appreciate it. Javascript is definately enabled in FF before you ask.

Many thanks,
Alex

 
parixit
said this on 25 Feb 2009 6:10:08 PM CST
Thanks !
This is exactly what I was looking for.



Leave a reply:
Your Name *: Email (private) *: Website:
Please copy the characters from the image below into the text field below. Doing this helps us prevent automated submissions.
Security Code: img