Lesson 16: Useful Tasks (II) – Form Validation

By Maria Antonietta Perna

A web form is a staple feature of almost any website today. Nothing can be more frustrating for your visitors than filling out all form fields, clicking the submit button, and have the entire form come back, emptied of all their carefully entered values, and displaying a cryptic error message expecting them to start all over again.

Any data that comes from users must be validated. This means that programs must check that no empty values are submitted, that submitted values are of the right type and length, etc. However, such checks are necessarily performed after the user has filled out and submitted the form to the server.

If the server is busy and takes a while before alerting the user that the form could not be accepted due to errors, users might get quite annoyed and decide not to come back to your otherwise fantastic website.

Thankfully, this rarely happens nowadays, thanks to JavaScript. In fact, although it's crucial that checking user input must be done on the server (e.g., php, .net, ruby, etc.), client-side JavaScript can do a lot to make the experience less painful and time consuming.

JavaScript runs in the user's browser, therefore it executes immediately. There's no need for the form to be submitted to the server before alerting the user that, for example, she has left one of the required fields empty.

In this lesson, you will learn how to:

  • make sure users fill out all required form fields;
  • make sure users enter a valid email.

How do I validate empty form fields?

In previous lessons you already performed some validation tasks. For example, you used isNaN() to make sure users entered a number data type. You also checked users didn't submit an empty value by using something like if (inputboxValue == "") { alert user...}. Let's see what else you could do to prevent users from submitting an empty form field.

Prepare an HTML document with a form and a button, like the one below:

		
		<!DOCTYPE html>
		<html>
		<head>
		<title>Lesson 16: Form validation</title>
		</head>
		<body>
		<h1>Lesson 16: Form validation</h1>
		
		<form id="myForm" action="#" method="post">
		
		<fieldset>
		
		<p><label for="txtName">First Name:</label>
		
		<input type="text" id="txtName" name="txtName" />
		
		</p>
		
		<p><input type="submit" value="Submit" onclick="validate()" /></p>
		
		</fieldset>
		  	
		</form>
		
		<script type="text/javascript">
		
		</script>
			
		</body>
		</html>
		
		

In between <script> tags write the validate() function as follows:

		
		function validate()
		
		{
		
		var userName = document.getElementById("txtName").value;
		
		//if the length of the string value is 0,
		
		//it means the user has entered no value:
		
		if (userName.length == 0)
		
		{
		
		alert("Please, enter your name");
		
		return false;
		
		}
		
		else
		
		{
		
		alert("Thank you, " + userName);
		
		}
		
		}
		
		

Save your work and run the page in a browser. Try submitting the form leaving the inputbox empty, and see what happens. Can you post the form? I hope not.

How do I validate email addresses?

Email addresses present a characteristic pattern. We know that they have one @ character and at least a dot ( . ) character.

More detailed patterns of email addresses, as well as of domain names, zip codes, telephone numbers, etc., can be validated using a powerful feature called regular expression. A treatment of regular expressions is beyond the scope of this tutorial. However, if you're interested the web offers a wealth of material on the subject.

In our code snippet we use some string manipulation methods to make sure the value entered by the user has an @ character and a dot.

		
		<!DOCTYPE html>
		<html>
		<head>
		<title>Lesson 16: Form validation</title>
		</head>
		<body>
		<h1>Lesson 16: Form validation</h1>
		
		<form id="myForm" action="#" method="post">
		
		<fieldset>
		
		<p><label for="txtEmail">Email:</label>
		
		<input type="text" id="txtEmail" name="txtEmail" />
		
		</p>
		
		<p><input type="submit" value="Submit" onclick="validate()" /></p>
		
		</fieldset>
		  	
		</form>
		
		<script type="text/javascript">
		
		</script>
			
		</body>
		</html>
		
		

Now, change the validate() function as follows:

		
		function validate()
		
		{
		
		var email = document.getElementById("txtEmail").value;
		
		//still check user entered a value
		
		if (email.length == 0)
		
		{
		
		alert("Please, enter an email address");
		
		return false;
		
		}
		
		//if the index position of the @  or . characters
		
		//is -1 (any value bigger than this, including 0,
		
		//means the character is present)
		
		else if (email.indexOf("@") == -1 || email.indexOf(".") == -1)
		
		{
		
		alert("Please, enter a valid email address");
		
		return false;
		
		}
		
		//if we get here, all went well
		
		else
		
		{
		
		alert("Thank you");
		
		}
		
		}
		
		

Save your work and preview the page in a browser. Now, enter an email address with no @ character or no dot charachter. Is your form submitting the value to the server? Hopefully, it isn't.

Try out: form validation demo

In this try out you will build a JavaScript program that checks user input (name and email) before web form submission. Prepare an HTML page containing a form with 2 inputboxes and a button, and add a paragraph with an id attribute called result to display messages to the user, like the one below:

		
		<!DOCTYPE html>
		<html>
		<head>
		<title>Lesson 16: Form validation</title>
		<script type="text/javascript" src="lesson16.js"></script>
		</head>
		<body>
		<h1>Lesson 16: Form validation</h1>
		
		<form id="myForm" action="#" method="post">
		
		<fieldset>
		
		<p><label for="txtName">Name:</label>
		
		<input type="text" id="txtName" name="txtName" />
		
		<p><label for="txtEmail">Email:</label>
		
		<input type="text" id="txtEmail" name="txtEmail" />
		
		</p>
		
		<p><input type="submit" value="Submit" /></p>
		
		</fieldset>
		  	
		</form>
		
		<p id="result"></p>
			
		</body>
		</html>
		
		

Now create the lesson16.js file. This contains 5 functions:

  1. init() binds the main function, validate(), to the form's onsubmit event;
  2. validate() examines the results returned by functions validating required fields and email format and displays an appropriate message;
  3. validateRequired(input) checks the input box has a value. It returns true if it has and false if it hasn't;
  4. validateEmail(email) checks the email is valid and returns true if it is, false if it isn't;
  5. writeMessage(text) displays a message to users when something goes wrong. It would be annoying to have alerts popping up every time an error occurs.
		
		function init()
		
		{
		
		var myForm = document.getElementById("myForm");
		
		myForm.onsubmit = validate;
		
		}
		
		
		
		/********************************/
		
		
		
		//bind init() function to onload event
		
		onload = init;
		
		
		
		/******************************************/
		
		
		
		//validate() checks answers from validateRequired()
		
		//and validateEmail() and displays appropriate messages.
		
		//If an error occurs program execution is stopped:
		
		function validate()
		
		{
		
		var name = document.getElementById("txtName").value;
		
		var email = document.getElementById("txtEmail").value;
		
		//validateRequired() and validateEmail()
		
		//return true/false values: create
		
		//variables to store the result
		
		var isRequiredNameSet = false;
		
		var isRequiredEmailSet = false;
		
		var isEmailValid = false;
		
		//create variable that holds message to display
		
		var message = "";
		
		isRequiredNameSet = validateRequired(name);
		
		isRequiredEmailSet = validateRequired(email);
		
		isEmailValid = validateEmail(email);
		
		//if all values are valid, prepare thank you message
		
		//and allow form submission
		
		if (isRequiredNameSet && isRequiredEmailSet && isEmailValid)
		
		{
		
		message = "Thank you, your details have been successfully posted!";
		
		}
		
		//if the name field is empty, write message to user and stop submission:
		
		else if (! isRequiredNameSet)
		
		{
		
		message = "Please, enter a name";
		
		writeMessage(message);	
		
		return false;
		
		}
		
		//If the email field is empty, write message to user and stop submission:
		
		else if (! isRequiredEmailSet)
		
		{
		
		message = "Please, enter an email";
		
		writeMessage(message);
		
		return false;
		
		}
		
		//If the email is not in a valid format (no @ or . characters),
		
		//we write a message to the user and stop program execution:
		
		else if (! isEmailValid)
		
		{
		
		message = "Please, enter a valid email";
		
		writeMessage(message);	
		
		return false;
		
		}
		
		//If we are here validation is successful:
		
		//display the thank you message with an alertbox:
		
		alert(message);
		
		}
		
		
		
		/***********************************************/
		
		
		
		//This function takes an argument
		
		//that represents the input element and checks
		
		//that it's not empty - it returns true if input is valid
		
		//and false if input is not valid:
		
		function validateRequired(input)
		
		{
		
		var isValid = false;
		
		if (input.length == 0)
		
		{
		
		isValid = false;
		
		}
		
		else
		
		{
		
		isValid = true;
		
		}
		
		return isValid;
		
		}
		
		
		
		/**********************************************/
		
		
		
		//validateEmail(email) checks the email is in valid
		
		//format and returns true if it is, false if it isn't:
		
		function validateEmail(email)
		
		{
		
		var isValid = false;
		
		if (email.indexOf("@") == -1 || email.indexOf(".") == -1)
		
		{
		
		isValid = false;
		
		}
		
		else
		
		{
		
		isValid = true;
		
		}
		
		return isValid;
		
		}
		
		
		
		/**********************************************/
		
		
		
		//writeMessage(text) has the message to
		
		//display to the user as argument, clears any previous
		
		//content from the paragraph with the id of result
		
		//and inserts the appropriate message for display
		
		//using DOM compliant techniques (lesson 14):
		
		function writeMessage(text)
		
		{
		
		var paragraph = document.getElementById("result");
		
		//The content inside the paragraph is the paragraph's
		
		//first child.  We check if there is any content and remove it:
		
		if (paragraph.firstChild)
		
		{
		
		paragraph.removeChild(paragraph.firstChild);
		
		}
		
		//Now we can create and append the new
		
		//message to display to the user:
		
		paragraph.appendChild(document.createTextNode(text));
		
		}
		
		

Save your work and preview it in a browser. You should see something like the page indicated by following the example link above.

Try clicking the submit button without filling out the form properly. If all goes as expected, you should not be able to submit your form unless it's values are complete and appropriate.

Obviously, your script can't verify an email address, but it can validate its format. Finally, keep in mind that for a detailed check of the email pattern, the best tool for the job is a regular expression.

Summary

You've come a long way in your JavaScript journey, well done!

Now get ready for the next lesson: time to start exploring the world of JavaScript animation with the timing functions.


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 15: Useful Tasks (I) – Setting and Retrieving Cookies

Lesson 17: JavaScript Timing Events >>