How to Build Powerful JavaScript Contact Forms with Validation Functions

javascriptbasicsIf people find your web pages informative or entertaining, they may offer to give you their names, email addresses and other valuable data. A user-friendly contact form makes that possible by enabling your readers to send you that data right from their browser.  It’s always a good idea to let code on your web server validate information that visitors send you. However, that doesn’t mean you can’t use JavaScript to verify data before users submit contact information. Client-side validation helps everyone by warning people of problems such as these:

  • Missing data
  • Invalid phone numbers
  • Invalid email addresses

There are many ways to identify errors and display them. The best method is one that makes it easy for site visitors to fill out your contact form quickly and submit it.   Want to pick up JavasScript quickly? Let Udemy help you. 

Insert Real-time Error Messages into Your Contact Form

A well-designed contact form displays information that helps people spot and correct specific data entry errors instantly. While you could display an alert window every time an error occurs, you’ll probably make site visitors happier by using a display method that shows error messages below input fields that have errors. Study the sample contact form below:

<form id="contactForm" method="post" action="mailto:MY_EMAIL_ADDRESS">
<div id="wrapperDiv"> <!— begin wrapper div -->
<div class="inputField"> <!—begin userName input field -->
 <input type="text" id="userName" onblur="checkForErrors(this)" />
 <span id="userName_ErrorMessage" class="errorMessage"> </span>
 </div> <!— end userName input field -->
 </div> <!— end wrapper div -->
<input type="button" value="Submit" onClick="submitForm()">

The first line of code defines your form, gives it an id and specifies the mailto email address that receives submitted information. Replace MY_EMAIL_ADDRESS with your email address.

The next line of code serves as a wrapper for all the form’s elements. Note the div on the third line of code. This div holds the elements that make up the form’s userName field and error message span. The div also references a CSS class named inputField.

The HTML span before the text box serves as a label for the text box. The text box’s id is userName. That’s an important id because your validation code will use that id to help the function that validates the fields detect errors. Each text box also has an onblur event handler. This causes JavaScript to call the checkForErrors function when a user’s cursor leaves an input field.

A div with an id of “userName_ErrorMessage” sits below the userName text box. This div contains a span that holds the error message associated with the userName text box field. This span references the errorMessage CSS class. Create the errorMessage and inputField classes by adding the following code to your HTML document’s head section:

.inputField {margin-top:13px;}
.errorMessage {color:red; display:none;}

The inputField class adds vertical spacing between each input field. Its value is 13 pixels in this example. The errorMessage class makes the color of all error messages red. More importantly, it makes all errorMessage spans invisible initially by setting their display values to “none.” If you view this form in a browser, you’ll see the following:

Name: ____________

The underline next to the Name label represents the userName input text box. You can add additional input fields and their associated error message spans to the form by using the userName block of code as a model. Here is how you’d add a code block that creates an email input text box and its error message span:

<div class="inputField"> <!—begin email input field -->
<input type="text" id="userEmail" onblur="checkForErrors(this)" />
<span id="userEmail_ErrorMessage" class="errorMessage"> </span>
</div> <!— end email input field -->

After you save your HTML document and view it in your browser, your form will display text boxes that enable them to enter a name and an email address, as seen below:

Name: ____________
Email: ____________

You will not see the spans that contain error messages unless an error occurs when you interact with the form. Learn how to manipulate Web page elements like a pro at Udemy

Check Fields for Errors

The checkForErrors function runs each time someone’s cursor leaves an input field. Here’s the code you need to create that function:

function checkForErrors(inputField) {

var errorMessageString = "";

/* check for missing name */

if ( == "userName" && hasValue(inputField) == "false")

errorMessageString = "Please enter your name";

/* check for missing email address */

if ( == "userEmail" && hasValue(inputField) == "false")

errorMessageString = "Please enter your email address";

/* check for valid email address */

var hasValidEmail = validEmail(inputField);

if ( == "userEmail" && hasValue(inputField) == "true" && validEmail(inputField) == "false")

errorMessageString = "Please enter a valid email address";

/* Clear error span */

var errorSpanId = + "_ErrorMessage";

var errorSpanObject = document.getElementById(errorSpanId);

errorSpanObject.textContent = ""; = "none";

/* Display error message if error exists */

if (errorMessageString != "") {

errorSpanObject.textContent = errorMessageString; = "block";



After the function blanks out the errorMessageString variable, the checkForErrors function examines the field passed to it and looks for an error in the input field passed to it by the field’s onblur event. For instance, if the incoming input field is the userName field, the checkForErrors function checks to see if that field is empty by calling the hasValue function. If the field is blank, the code sets the value of the errorMessageString string to the error message you’d like people to see if the userName field is blank.

The end of the function has code that looks for a non-blank value in the errorMessageString. If it finds one, it makes an error message appear on the contact form. It does this by figuring out the id of the error message span associated with the field. For example, if the field is userName, the code appends “_ErrorMessage” to “userName” to get “userName_ErrorMessage.” After the code gets the error message span’s id, it obtains a reference to the span and sets its display value to “block” to make the span visible. Finally, code at the end of the function sets the span’s textContent value to the value stored in the errorMessageString variable.  Need to learn more about JavaScript methods? Let Udemy help you.

Perform Special Error Checking

In many of the fields you check, you may only need to verify that a user entered data into the field. Review the checkForErrors function again and you’ll see a call to the hasValue function. That function, shown below, returns true if the field you’re checking has a value. Otherwise, it returns false:

function hasValue(inputField) {

var fieldHasValue = "true";

var trimmedInput = inputField.value.trim();

if (inputField.value == null || inputField.value == undefined || trimmedInput == "")

fieldHasValue = "false";

return fieldHasValue;


The checkForErrors function also calls the validEmail function to verify that the email address someone enters is valid. That function appears below:

function validEmail(inputField) {

var fieldHasValidEmail = "true";

var trimmedInput = inputField.value.trim();

var dotLoc=trimmedInput.lastIndexOf(".");

var atSignLoc = trimmedInput.indexOf("@");

if (atSignLoc < 1 || ( dotLoc - atSignLoc < 2 ) )

fieldHasValidEmail = "false";

return fieldHasValidEmail;


This code looks for an ampersand inside the email address string and a period. Both characters must be in character positions that are greater than position zero. The ampersand must also appear before the period. This is an example of a simple email error checking algorithm. However, it can help identify many invalid email addresses that people might enter.

Extend the Error Correction Model

Follow the model described in these sections to add other input fields to the checkForErrors function. Each field will reside in its code block as seen in the examples that verify name and email address. For instance, if one of your fields must have numeric data, add a code block that checks for numeric values. Because error messages appear immediately as users work with your contact form, they receive instantaneous feedback and can fill out the form quickly. As site visitors correct errors, they disappear. They can then click the “Submit” button to submit the form data. Review the form’s HTML again and you’ll see that the Submit button’s onclick event calls the following function:

function submitForm() {
return false;

The first line of code retrieves a reference to your form and submits it dynamically.