Udemy logo

javascriptsplitBefore JavaScript, when you entered values on a website form, those values had to be passed to the server and if there was something wrong with the values or if there was data missing, then the server would return the information so that the user could correct the mistakes and include the missing information. This process took time and also caused extra load on the server.

JavaScript included the form validation functions to validate the data before it is sent to the server thus saving the client time and saving the server from becoming overloaded. The form validation function allows programmers to include functions within their web forms to check that the data entered by the user meets certain criterion.

This tutorial will cover some of the most common form validation functions available in JavaScript. To follow the concepts in this tutorial, we suggest you have a basic knowledge of JavaScript. A great course for JavaScript is JavaScript for Absolute Beginners.

How to use Validate to ensure fields are filled in

One of the first things you want to validate as a programmer is that your users have filled in the required form fields. To validate that a field has not been left empty by your users you need to create a function that will check that that particular field has not been left blank. This is the code you could use to create that function:

<script>
// Create a function to validate the form
function validateForm()
  {
        // Assign variables for the required fields
        var x=document.forms["testForm"]["fname"].value;
        //Check that the variables are not empty
        if (x==null || x=="")
        {
              alert("Please enter your name!");  
              return false;
        }
  }
</script>

Now that we have a function we can add our function to a form to validate the user input.

<!DOCTYPE html>
<html>
<head>
<script>
// Create a function to validate the form
function validateForm()
  {
        // Assign variables for the required fields
        var x=document.forms["testForm"]["fname"].value;
        //Check that the variables are not empty
        if (x==null || x=="")
        {
              alert("Please enter your name!");  
              return false;
        }
  }
</script>
</head>
<body>
//Create a form using HTML and include our validateForm() function
<form name="testForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

If the user clicks submit without entering data in the field then the program will bring up an alert box as follows:

For more information on how to create forms and functions in JavaScript and HTML, sign up for the JavaScript Fundamentals today.

How to use validate to validate a valid email address

To verify an email address we need to check various elements within the format of the email address that the user has entered. An email address must contain the users’ email username. The username must be followed by an “@” character. The email must then contain the domain name. And finally the email must contain a “.” followed by the domain type. An email address therefore generally conforms to the following formatting:

To validate an email address we therefore need to make sure that the email address contains an “@” character. We also need to check that the address contains at least a few characters before the “@” character to ensure the user has included their username.  We need to make sure that it contains a few characters for the domain name. And finally we need to check that it contains characters after the full stop.

<script>
function validateEmail()
  {
  // Create a variable to hold user input
  var x=document.forms["testForm"]["email"].value;
  // Create a variable to return the numerical value of @
  // within the variable
  var atpos=x.indexOf("@");
  // Create a variable to return the numerical value of .
  // within the variable
  var dotpos=x.lastIndexOf(".");
  // Compare the numerical values
  if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
        {
        alert("Not a valid e-mail address");
        return false;
        }
  }
</script>

The above script validates the email input by creating a variable that contains the email address that the user has entered. The script also creates a variable that holds the position of the “@” character. It also creates a variable that holds the position of the “.” character within the input that the user has entered. So essentially we now have the variable and we have the positions of the “.” and the “@” within that variable. The script now uses those numerical values to compare the positions of those variables within the user input variable.

The script makes sure that there are at least a few characters before the @ character using the “atpos<1” statement. It also makes sure that the “.” appears after the “@” character and that there are characters between these two using the dotpos<atpos+2 statement. And finally it checks that there are at least 2 characters after the “.” using the total variable length.

If the user enters an invalid email address like: @mail.com then the user will see the following alert box:

How to use the validate function to validate phone numbers

In our final example we will use the validate function to validate a phone number. A phone number has at least 10 numbers and a phone number can only contain valid numerical characters. Here is the HTML and script we will use to validate a phone number:

<!DOCTYPE html>
<html>
<head>
<script>
function validatePhone()
  {
  // Create a variable to hold user phone number input
  var x=document.forms["testForm"]["phone"].value;
  // Remove all of the "-" characters
  // within the variable
  var stripped = x.replace(/[\(\)\.\-\ ]/g, '');
  // Use the if and if else statements to check our phone number
  // Use If to check the field has something filled in and isn’t blank
    if (x == "")
       {
        alert("You did not enter a number!");
        return false;
        }
  // Use else if to check that the phone number is a number
  // and doesn’t contain other characters
     else if (isNaN(parseInt(stripped)))
           {
        alert("Phone Number can only contain numbers!");
        return false;
        }
  // Use else if to check that the phone number entered is 10 digits long
    else if (!(stripped.length == 10))
      {
        alert("Phone Number contains wrong amount of numbers!");
        return false;
        }
  }
</script>
<body>
<form name="testForm" action="demo_form.asp" onsubmit="return validatePhone();" method="post">
Phone: <input type="text" name="phone">
<input type="submit" value="Submit">
</form>
</body>
</html>

The above script uses some advanced JavaScript functions and features. To learn to harness the power of JavaScript, sign up for JavaScript with BackboneJS and Bootstrap CSS – Advanced today.

Validation of Forms is simple with JavaScript

Whether you are learning JavaScript from Scratch or want to create more advanced forms, validation is an essential part of creating forms that work for the user and the server.

JavaScript included the form validation functions to validate the data before it is sent to the server thus saving the client time and saving the server from becoming overloaded. The form validation function allows programmers to include functions within their web forms to check that the data entered by the user meets certain criterion.

Page Last Updated: February 2014

JavaScript students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo