Home » Code » Really simple inline Javascript validation

Really simple inline Javascript validation

Posted by on August 8th, 2012

Really simple inline Javascript validation
Just about any website or web application will require user input in one form or another. Whether it’s filling in a contact form or entering profile details into a new application, handling input errors can be the difference between a good or a bad user experience.

Have you ever filled in a huge form online, only to submit it and find that there was an error so you have to start again? Frustrating, isn’t it? It is these kind of fundamental errors that stop people returning to your website.

A much better way of solving this problem is to include inline validation that checks the user’s input as she progresses. This alerts the user to any errors and allows her to correct her errors before proceeding and losing her progress.

Inline validation powered by Javascript can be incredibly easy to implement, so there really is no excuse for not making your user’s lives as easy as possible.

Here is a tutorial for building your own Javascript validation that you can use on any input on your website or web application. I’ve intentionally kept it as easy, simple and lightweight as possible.

Creating your page

For this tutorial I’m just going to include all of the HTML and Javascript in one file to keep things simple.

So to start off, create yourself a little HTML file, like this.

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Validation tutorial</title>
	<script>
		// JS
	</script>
</head>
<body>

</body>
</html>

Create the form

Next we need to a create an input field to validate. Create a form and an input field to allow you to enter your name.

<form action="">
	<fieldset>
		<label for="name">Name</label>
		<input type="text" name="name" id="name" />
	</fieldset>
</form>

Next we need to add the onblur Javascript event to the input field. The onblur event allows you to run Javascript code when the user clicks away from the field. In this case, we want to be able to validate what the user has entered into the field, but we only want to do that when she has finished typing and has moved on.

Update your input field so it looks like this.

<input type="text" name="name" id="name" onblur="validateName(name)" />

As you can see, I’ve already named the Javascript function that we are going to make in a minute and I’ve passed in the name of the the field, in this case “name”.

Introducing the Javascript

Next we need to create the Javascript function.

In between the tags at the top of the page, type the following code.

function validateName(x){
	alert(document.getElementById(x).value);
}	

Now save your file and open it in the browser. Enter some text into the input field and click away from the field. An alert box should appear with the text you entered.

So as you can see…

  • We created an input field
  • Added an onblur event which is triggered when the user clicks away
  • We then used a Javascript function to display the contents of the input in an alert box.

So hopefully you can see how the Javascript is run when it is triggered, and how we are able to get whatever the user has typed into the input box and do something with it.

Next I’ll show you how to validate the input.

Delete the following line from your Javascript.

alert(document.getElementById(x).value);

Javascript Regular Expressions

In order to validate the input, we have to test it against a set of rules that define a pass or fail. For example, you don’t want your users to enter & or @ or % into your name field because these characters don’t belong there.

In order to create a set of rules we use a Regular Expression (Regex). A Regular Expression is a way of matching an input to a set of rules. If the input matches the pattern it will return true, but if it does not, it will return false. So in the above example, if the input contained an @ when the pattern does not include an @ the test would return false and the validation would fail.

To create a validation for your name field, type the following line into your validateName() function.

var re = /[A-Za-z -']$/;

In the above line of code, we create a variable called re and assign it the regex of any capital letter (A-Z), any lower case letter (a-z), a space, a hyphen or an apostrophe.

With this regex rule saved, we can then run a test on our input to see if what was entered matches our defined rule.

Type the following code after the previous line.

if(re.test(document.getElementById(x).value)){
	document.getElementById(x).style.background ='#ccffcc';
	return true;
}else{
	document.getElementById(x).style.background ='#e35152';
	return false;	
}

Here’s how the above code breaks down.

if(re.test(document.getElementById(x).value)){

We test to see if the input value matches our rule.

If it does, we change the input box’s background to green.

document.getElementById(x).style.background ='#ccffcc';
return true;

But if it doesn’t, we turn the input box red.

}else{
	document.getElementById(x).style.background ='#e35152';
	return false;	
}

Save this out and refresh the page in your browser. You should now have a swanky input box that validates and gives a visual feedback to the user to tell them if their input was accepted or not.

Including a prompt

We’ve added a huge amount of usability to our form already, but there is still more we can do.

Not every input field will have obvious rules. For example, you might have a username field where you have a very precise set of allowed characters. In this instance, it is important to give your user some kind of message to help them complete the form. Without this prompt, you are likely going to annoy your user if they are repeatedly failing your validation test.

To add a validation prompt, add the following line of code to your form, just under your input field.

<span id="nameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span>

Next add the following line to the else branch of your if else statement in your Javascript.

document.getElementById(x + 'Error').style.display = "block";

Save your file and fresh your browser. You should now be given a prompt when you enter invalid characters.

Finally add the following line to the if branch of your if else statement.

document.getElementById(x + 'Error').style.display = "none";

This will clean up the prompt message once the user corrects their mistake.

Validation on form submission

The validation you’ve added so far is great because it allows the user to correct their mistakes as they progress. The next step is to prevent the form from being submitted if any of the validation rules are broken.

This is handy because we don’t really want to allow our user to submit a form with invalid data. Once the form is validated on the server side, it should spit it back out with an error message. However, we can stop it from ever getting this far by validating on the client side too.

Client side validation

So the first thing we need to do is to create a button to allow our form to be submitted.

<input type="submit" id="submit" name="submit" value="Submit" />

Next we need to add an onsubmit event. This is very similar to the onblur event we created earlier, the only difference is it is run only when the form is submitted.

Update your form tag so it looks like this.

<form action="" onsubmit="return validateForm()">

More Javascript

Now we need to create the validateForm() function that will check the entire form for valid date.

In between the script tags, write the following.

function validateForm(){

}

Next we need to create an error count.

// Set error catcher
var error = 0;

Next we run our validateName() function.

// Check name
if(!validateName('name')){
	document.getElementById('nameError').style.display = "block";
	error++;
}

This runs the validateName() function on the name input field. If it returns false we know that the input field did not validate and so we display our error prompt and increase the error counter by 1.

Finally we create a little catch so if there are errors the form will not submit.

// Don't submit form if there are errors
if(error > 0){
	return false;
}

Now when you save out your form you shouldn’t be able to submit it if there are errors. To successfully submit the form you need to correct all the errors so the fields turn green.

Extending our Javascript validation

You know have a full working example of inline validation and client side validation that you can implement on your website’s forms.

Hopefully this has given you enough of a start to extend the code to meet your requirements.

Here are some further Javascript validation functions that you can add to you code to extend it further and help you get started making some really awesome inline validation.

Validate email addresses

HTML

<fieldset>
	<label for="email">Email</label>
	<input type="text" name="email" id="email" onblur="validateEmail(value)" />
	<span id="emailError" style="display: none;">You must enter a valid email address</span>
</fieldset>	

Javascript

// Validate email
function validateEmail(email){ 
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	if(re.test(email)){
		document.getElementById('email').style.background ='#ccffcc';
		document.getElementById('emailError').style.display = "none";
		return true;
	}else{
		document.getElementById('email').style.background ='#e35152';
		return false;
	}
}

Validate dropdown boxes

HTML

<fieldset>
	<label for="animal">Favourite Animal</label>
	<select name="animal" id="animal" onblur="validateSelect(name)">
		<option value="">Animals</option>
		<option value="cat">Cat</option>
		<option value="dog">Dog</option>
		<option value="badger">Badger</option>
	</select>
	<span class="validateError" id="animalError" style="display: none;">You must select your favourite animal</span>
</fieldset>

Javascript

// Validate Select boxes
function validateSelect(x){
	if(document.getElementById(x).selectedIndex !== 0){
		document.getElementById(x).style.background ='#ccffcc';
		document.getElementById(x + 'Error').style.display = "none";
		return true;
	}else{
		document.getElementById(x).style.background ='#e35152';
		return false;	
	}
}

Validate Radio buttons

HTML

<fieldset>
	<label for="hand">Left or Right handed?</label>
	<ul>
		<li>
			<input type="radio" name="hand" id="left" value="Left" onblur="validateRadio(id)" />
			<label for="left">Left handed</label>
		</li>
		<li>
			<input type="radio" name="hand" id="right" value="Right" onblur="validateRadio(id)" />
			<label for="right">Right handed</label>
		</li>
	</ul>
	<span class="validateError" id="handError" style="display: none;">Which hand do you use?</span>
</fieldset>

Javascript

function validateRadio(x){
	if(document.getElementById(x).checked){
		return true;
	}else{
		return false;
	}
}

Validate Checkboxes

<fieldset>
	<label for="terms">Terms and Conditions</label>
	<ul>
		<li>
			<input type="checkbox" name="terms" id="accept" value="accept" onblur="validateCheckbox(id)" />
			<label for="accept">Accept our <a href="#">Terms and Conditions</a></label>
		</li>
	</ul>
	<span class="validateError" id="termsError" style="display: none;">You need to accept our terms and conditions</span>
</fieldset>

Javascript

function validateCheckbox(x){
	if(document.getElementById(x).checked){
		return true;
	}
	return false;
}

Validate your entire form

And finally, add the following code to your validateForm() function to validate your whole form when it is submitted.

// Validate email
if(!validateEmail(document.getElementById('email').value)){
	document.getElementById('emailError').style.display = "block";
	error++;
}
// Validate Radio
if(validateRadio('left')){

}else if(validateRadio('right')){
	
}else{
	document.getElementById('handError').style.display = "block";
	error++;
}
// Validate Checkbox
if(!validateCheckbox('accept')){
	document.getElementById('termsError').style.display = "block";
	error++;
}

The full code

Here is the full code.

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Validation tutorial</title>
	<script>
		function validateName(x){
			// Validation rule
			var re = /[A-Za-z -']$/;
			// Check input
			if(re.test(document.getElementById(x).value)){
				// Style green
				document.getElementById(x).style.background ='#ccffcc';
				// Hide error prompt
				document.getElementById(x + 'Error').style.display = "none";
				return true;
			}else{
				// Style red
				document.getElementById(x).style.background ='#e35152';
				// Show error prompt
				document.getElementById(x + 'Error').style.display = "block";
				return false;	
			}
		}
		// Validate email
		function validateEmail(email){ 
			var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			if(re.test(email)){
				document.getElementById('email').style.background ='#ccffcc';
				document.getElementById('emailError').style.display = "none";
				return true;
			}else{
				document.getElementById('email').style.background ='#e35152';
				return false;
			}
		}
		// Validate Select boxes
		function validateSelect(x){
			if(document.getElementById(x).selectedIndex !== 0){
				document.getElementById(x).style.background ='#ccffcc';
				document.getElementById(x + 'Error').style.display = "none";
				return true;
		    }else{
				document.getElementById(x).style.background ='#e35152';
				return false;	
			}
		}
		function validateRadio(x){
			if(document.getElementById(x).checked){
				return true;
			}else{
				return false;
			}
		}
		function validateCheckbox(x){
			if(document.getElementById(x).checked){
				return true;
			}
			return false;
		}		
		function validateForm(){
			// Set error catcher
			var error = 0;
			// Check name
			if(!validateName('name')){
				document.getElementById('nameError').style.display = "block";
				error++;
			}
			// Validate email
			if(!validateEmail(document.getElementById('email').value)){
				document.getElementById('emailError').style.display = "block";
				error++;
			}
			// Validate animal dropdown box
			if(!validateSelect('animal')){
				document.getElementById('animalError').style.display = "block";
				error++;
			}
			// Validate Radio
			if(validateRadio('left')){

			}else if(validateRadio('right')){
				
			}else{
				document.getElementById('handError').style.display = "block";
				error++;
			}
			if(!validateCheckbox('accept')){
				document.getElementById('termsError').style.display = "block";
				error++;
			}
			// Don't submit form if there are errors
			if(error > 0){
				return false;
			}
		}			
	</script>
</head>
<body>
	<form action="" onsubmit="return validateForm()">
		<fieldset>
			<label for="name">Name</label>
			<input type="text" name="name" id="name" onblur="validateName(name)" />
			<span id="nameError" style="display: none;">You can only use alphabetic characters, hyphens and apostrophes</span>
		</fieldset>
		<fieldset>
			<label for="email">Email</label>
			<input type="text" name="email" id="email" onblur="validateEmail(value)" />
			<span id="emailError" style="display: none;">You must enter a valid email address</span>
		</fieldset>	
		<fieldset>
			<label for="animal">Favourite Animal</label>
			<select name="animal" id="animal" onblur="validateSelect(name)">
				<option value="">Animals</option>
				<option value="cat">Cat</option>
				<option value="dog">Dog</option>
				<option value="badger">Badger</option>
			</select>
			<span class="validateError" id="animalError" style="display: none;">You must select your favourite animal</span>
		</fieldset>	
		<fieldset>
			<label for="hand">Left or Right handed?</label>
			<ul>
				<li>
					<input type="radio" name="hand" id="left" value="Left" onblur="validateRadio(id)" />
					<label for="left">Left handed</label>
				</li>
				<li>
					<input type="radio" name="hand" id="right" value="Right" onblur="validateRadio(id)" />
					<label for="right">Right handed</label>
				</li>
			</ul>
			<span class="validateError" id="handError" style="display: none;">Which hand do you use?</span>
		</fieldset>
		<fieldset>
			<label for="terms">Terms and Conditions</label>
			<ul>
				<li>
					<input type="checkbox" name="terms" id="accept" value="accept" onblur="validateCheckbox(id)" />
					<label for="accept">Accept our <a href="#">Terms and Conditions</a></label>
				</li>
			</ul>
			<span class="validateError" id="termsError" style="display: none;">You need to accept our terms and conditions</span>
		</fieldset>		
		<fieldset>
			<input type="submit" id="submit" name="submit" value="Submit" />
		</fieldset>		
	</form>
</body>
</html>

Philip Brown

Hey, I'm Philip Brown, a designer and developer from Durham, England. I create websites and web based applications from the ground up. In 2011 I founded a company called Yellow Flag. If you want to find out more about me, you can follow me on Twitter or Google Plus.

Join the Culttt

Become an insider and join the Culttt

  • Rohit

    hiii. i m rohit from i suugest you to please add a demo

    • http://culttt.com/ Philip Brown

      Hi Rohit,

      You’re right I should, I really need to get round to that.

  • Rishika

    This proved quite helpful ! But the above procedure doesn’t apply to anexternal Javascript file . If you could just be kind enough to add that too. Thanks !

    • http://culttt.com/ Philip Brown

      Hi Riskika, all you would have to do is to reference an external file in the head section of the page, nothing needs to change.

  • Kathryn

    Thank you! This was simple, easy to understand and helped a ton.

    • http://culttt.com/ Philip Brown

      Hi Kathryn, glad it helped! The simplest examples are often the best.

  • Kaelin

    This was really really helpful. I wound up adding my own random math captcha, multiple error responses depending upon different inputs, and processing with ajax. Thanks so much for the tutorial! Would you consider writing one on server side validation to go with it? :)

    • http://culttt.com/ Philip Brown

      Hey, glad it helped you! Sounds like you’ve made some nice extensions.

      Server side validation really depends on what language you are wanting to use. I’m guessing there will probably already be some pretty good tutorials online for what you are looking for.

      Take a look at my first big “Building a web application series” http://culttt.com/2013/04/29/getting-started-with-laravel-4/

      I’ll be covering server side validation soon, so you might be able to get what you need from that :)

  • vanherckthomas

    Hey, this tutorial is awesome! Just one question: after the validation I want to use php for sending the form back to me as an email. I already have the php file, but where do I need to link to my form and/or javascript?

    Thanks in advance,

    Thomas

    • http://culttt.com/ Philip Brown

      Hi Thomas, you would just add an action to your form, like this:

  • Lazarix69

    How can I get it to do a focus() event when it finds an error, and go to whichever error it finds first?

    • http://culttt.com/ Philip Brown

      You would just call the focus method when a validation fails. Create a new method for setting the focus and pass it the reference to the field. Then call the method when a validation rule fails.

      • Lazarix69

        Thanks for the reply Philip!

        If I understand you correctly, I would need to make:

        if(error > 0){

        return false;

        }

        look like

        if(error > 0){

        return false;
        focus();
        }

        but i’m not sure how to create a new method for setting the focus. Could you give an example using the name and email fields from your tutorial?

        By the way, the whole thing is enlightening and is the first time that i’ve been able to understand and implement inline validation in a nice way!

        • Lazarix69

          Ok, I’ve sorted it:

          You just add in the following as part of yourvalidateform function

          document.getElementById(‘name’).focus();

          So, the “name” field validation would now look like this:

          // Check name

          if(!validateName('name')){

          document.getElementById('nameError').style.display = "block";

          document.getElementById('name').focus();

          error++;

          }

          • http://culttt.com/ Philip Brown

            Excellent. I would perhaps extract it into it’s own function so that you don’t have to repeat yourself :)

  • Lfhj

    Nice code, a demo will be great

    • http://culttt.com/ Philip Brown

      Thanks :)

  • Stevo

    I happened across this post and it is awesome – helped a lot, so thanks! One question. I have a site with three radio buttons, not just the two. In this case, how would it be handled? Say the options were “left hand only”, “right hand only” or “ambidextrous”, how could the code still validate that one of the three options is selected? I am guessing it might involve nested if-else statements, but could you please help me out with some code to do the job? Thanks in advance.

    • http://culttt.com/ Philip Brown

      Yeah you could do something like that. To be honest I wrote this post a long time ago, so I probably wouldn’t handle it like that.

      I would probably use jQuery validation. Using something like that (or even creating your own jQuery validation) is going to be better in the long run.

  • Matias Vad

    This is a great tutorial and it works perfectly!
    However I have a problem, since I have a form that isn’t being submitted, but rather inputted through a URL. And for that to happen I need to use a type=”button” as my submit-button, instead of type=”submit” .. When I switch this, I try using an “onclick”-event rather than an “onsubmit”, but this isn’t working.
    Do you have any tips?

  • Michele Rose

    Great tutorial! But I’ve run into a problem. I want to use the same validateName function to apply to two fields. One field is a Name field and the other is a Company Name field. Is this possible? Thanks!

    • http://culttt.com/ Philip Brown

      Yeah, you just pass the name of the field as the argument :)

      • Michele Rose

        Thanks! I’ll try that!

        • http://culttt.com/ Philip Brown

          No problem :)

Supported by