Form Validation Using Javascript

Form Validation Using Javascript: Hello, my name is Julie Spencer. I work as a Developer at VeePN VPN company. I was one of the developers who made VPN for Windows and VPN Сhrome extension. My field of activity also includes the development of contact forms for the sites. Today I will tell you about form validation using JavaScript.

Form validation used to take place on the server after the client had provided all of the required information and then clicked the Submit button.

Form Validation Using Javascript
Form Validation Using Javascript

Suppose the server discovers that part of the information given by the client was incorrect or simply missing. In that case, it will have to send all of the information back to the client and request that the form be resubmitted with the correct information. This was a very big operation that placed an excessive strain on the server.

Client-side Form Validation Using Javascript

JavaScript offers a method of validating form data on the client’s computer before sending it to the webserver through the internet. Form validation is often used to accomplish two tasks.

Basic Validation – First and foremost, the form must be double-checked to ensure that all essential data has been put into each area on the form. Simply looping over each field in the form and checking for data would be sufficient here.

Data Format Validation – The second step is to validate the data that has been provided to ensure that it is in the right form and value. To verify the accuracy of the data, further logic would have to be used.

In any web application, validation of form data is of two types. The first one is client-side validation, and the second one is server-side validation. This post explains client-side validation, where we use JavaScript to validate user data and show errors to the user before form submission.

Client-side validation using JavaScript is easier and quicker (the browser doesn’t have to connect to the server to validate the form).

Read Also:  javascript remove last comma from Array

As part of form validations, usually, we do the following validations:

  1. Validate Username
  2. Validate Email address
  3. Validate Password
  4. Validate Phone Number
  5. Validate Numeric Fields
  6. Validate Empty fields or Required fields

Javascript to validate Username (Permit only usernames that are between 5 and 15 characters and allow only letters, numbers and underscores)
This Javascript is used to validate a username that contains 5 and 15 characters and allow only letters, numbers and underscores. Below is the code for the validation of username in Javascript Form.

<script type="text/javascript">
function validateUsername() {
    // allow letters, numbers, and underscores
    var illegalChars = /\W/; 
    var error = "";
    var username = document.getElementById('username').value;
    if (username == "") {
        error = "You didn't enter a username.\n";
    } else if ((username.length < 5) || (username.length > 15)) {
        error = "The username is the wrong length.\n";
    } else if (illegalChars.test(username)) {
        error = "The username contains illegal characters.\n";
    }
    return error;
}
</script>

JavaScript to validate Email Address

When verifying a JavaScript form, it is important to consider the validity of the email address. This page has covered how to validate an email address using JavaScript.

An email is a string of characters (a subset of ASCII characters) divided into two sections by the @ sign. An email address with the subject “email” and the domain name, which is email.

  • The email part contains the following ASCII characters.
  • Uppercase (A-Z) and lowercase (a-z) English letters.
  • Digits (0-9).
  • Characters _ –

<script type="text/javascript">
function validateEmail() {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var error = "";
   var address = document.getElementById('email').value;
   if(reg.test(address) == false) {
      error = "Invalid Email Address.\n";
   }else{
      error = "Valid Email Address.\n";
   }
   return error;
}
</script>

JavaScript to validate Password (Password should not be blank and allow only letters and numbers. Password must contain one numeral)
When filling out a form, it is sometimes necessary to validate the password.

Passwords may be created using various methods, with their structures ranging from basic, fair, or strong.

A password structure is checked for validity using JavaScript codes and regular expressions.

Check a password that is between 5 and 15 characters and that has only letters, numbers and should not be blank.

Read Also:  alert message in php - Displaying An Alert Message Box

<script type="text/javascript">
function validatePassword() {
    // allow only letters and numbers 
    var illegalChars = /[\W_]/;
    var password = document.getElementById('password').value;
    var error = "";
    if (password == "") {
        error = "You didn't enter a password.\n";
    } else if (illegalChars.test(password)) {
        error = "The password contains illegal characters.\n";
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The password must contain at least one numeral.\n";
    }
    return error;
}  
</script>

JavaScript to validate Phone Number (The phone number should contain only numbers, and it should be of 10 digits)
When evaluating a Javascript form, it is critical to consider the phone number that is being validated. Using JavaScript, we can verify a phone number in a variety of formats.

First, we confirm a phone number with ten digits that does not have a comma, spaces, or punctuation, and that does not have a Plus sign in front of the number. All that is required is that you validate your phone number and only phone numbers with 10 digits will be permitted. The function is shown below.

<script type="text/javascript">
function validatePhone() {
   var phone = document.getElementById('phone').value;
   var error = "";
   var stripped = phone.replace(/[\(\)\.\-\ ]/g, '');     
   if (phone == "") {
        error = "You didn't enter a phone number.\n";
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number should contain only numbers.\n";
    } else if (!(stripped.length == 10)) {
        error = "The phone number is of wrong length. Make sure you included 
        an area code.\n";
    } 
    return error;
}
</script>

JavaScript to validate Numeric Fields

We have used the isNaN() method to validate that the NumericField contains just numeric values. isNan() accepts text-field data as an argument, and if the data is a number, isNaN() returns true; otherwise, it returns false. If the data is not a number or a mix of numbers and alphabets, isNan() returns false.

The code below is written in JavaScript that checks if a text field includes a digit or not.

<script type="text/javascript">
function validateNumericField() {
     var fieldValue = document.getElementById('number').value;
     var error = "";
     if (isNaN(parseInt(fieldValue))) {
        error = "Not a valid numeric value.\n";
     } 
     return error;
}
</script>

JavaScript to validate Empty or Required Fields

If an input field (username) is left empty, this function generates an alert message and returns false, preventing the form from being submitted:

Read Also:  strstr in php

<script type="text/javascript">
function validateEmptyOrRequiredFields() {
var value = document.getElementById('username').value;
var error = "";
if (value == null || value == "")
  {
  error = "Username cannot be empty.\n";
  }
  return error;
}
</script>

Simple Example of HTML Form

HTML Form controls text fields, password fields, checkboxes, radio buttons, a submit button, menus, and other controls.

When a user fills out an HTML form, the data is transmitted to the server for processing, and the data includes information such as the user’s name, email address, password, phone number, and so on. Below is the simple code for the HTML Form.

<html>
<head>
<title>Javascript Form Validation</title>
<script type="text/javascript">
function validateFormOnSubmit() {
  var reason = "";
  reason += validateUsername();
  reason += validatePassword();
  reason += validateEmail();
  reason += validatePhone();
  reason += validateEmptyOrRequiredFields();
  reason += validateNumericField();
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  } else {
    return true;
  }
}
</script>
</head>
<body>
<h1>Validate Form</h1>
<form name="detailForm" onsubmit="return validateFormOnSubmit()" action="test.htm">
<table summary="Form">
  <tbody>
  <tr>
    <td><label for="username">Username:</label></td>
    <td><input name="username" size="35" maxlength="50" type="text"
            id="username"></td>
  </tr>   
  <tr>
    <td><label for="pwd">Password</label></td>
    <td><input name="pwd" size="35" maxlength="25" type="password"
            id="password"></td>
  </tr>   
  <tr>
    <td><label for="email">Email:</label></td>
    <td><input name="email" size="35" maxlength="30" type="text" id="email"></td>
  </tr>
  <tr>
    <td>
        <label for="from">Age :</label></td>
    <td><input name="from" size="35" maxlength="50" type="text" id="number"></td>
  </tr>
  <tr>
    <td><label for="phone">Phone:</label></td>
    <td><input name="phone" size="35" maxlength="25" type="text" id="phone"></td>
  </tr>   
  <tr>
    <td> </td>
    <td><input name="Submit" value="Submit" type="submit" ></td>
    <td> </td>
  </tr> 
  </tbody>
</table>
</form> 
</body>
</html>

Now you know how to create forms through JavaScript. Form Validation Using Javascript Try it out and comment down below if you have any queries about it.