javascript form validation

Javascript is highly used in form validation especially in static sides where there's no server side script running. It's also used with server side languages though. Basically in other fields, we check if there's any field empty but with input type email we can check the positioning of @ and . symbol to validate them.

Form validation can be divided into following categories.

  • Email Validation - Match with the general pattern of an email to validate input.
  • Empty Validation - Check any of the form field is being sent empty.
  • Value Length Validation - Check if the value being sent has the required length of characters.
  • Value Format Validation - Check if the value being sent has any special characters included.

We can trigger the validation function with onchange or onsubmit event.

Javascript Email Validation

Lets have a look at the form validation example first. We added a input field which holds onChange, an event handler that triggers the function emailValidation.

<input type="email" name="email" placeholder="Email Address" id="email_field" onChange="return emailValidation()">
<span id="email-error"></span>
<script>
function emailValidation()
{
  value = document.getElementById('email_field').value;
  apos=value.indexOf("@"); 
  dotpos=value.lastIndexOf(".");
  lastpos=value.length-1;
  if (apos < 1 || dotpos-apos < 2 || lastpos-dotpos > 3 || lastpos-dotpos < 2){
      document.getElementById("email-error").innerHTML = "Invalid Email Address";
      return false;
    } else {
      return true;
  }
}
</script> 

At first, we stored the input value in a variable named value. Then, we check the positioning of @ symbol using value.indexOf("@") that counts the individual characters in the stored value as if they were in array. We also counted the positioning of . symbol in the value using the same method. Finally, we counted the position of the last character in the value using value.length-1, which will give us the positioning of the last character in the string.

Now, we've got the positioning values of three elements i.e. "@", "." and the last character as digits, we can create a combination of logical statement to validate email. Here's an example.

  • if(apos < 1) - If the position of @ symbol is at the beginning of the email address like @something.com, then the email address is not valid.
  • if(dotpos-apos < 2) - If the character difference between the position of . and @ is less than 2 like something@a.com, then it can't be a valid email address.
  • lastpos-dotpos > 3 || lastpos-dotpos < 2- If the character difference between the last letter of the string and "." symbol is greater than 3 like something@something.something ot less than 2 like something@something.c, it can't be a valid email address.

You can opt for any method to display the error message.

Empty / Value Length and Format Validation

Empty validation is an easy one to do. Simply check if the field is empty of not. Lets make it interesting by combining it with the value length and format validation as well as special characters vaidation.

<input type="text" name="user" id="user_field" onChange="return userValidation()" placeholder="Username">
<span id="user-error"></span>
<script>
function userValidation()
{
  username = document.getElementById('user_field').value;
  var format = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
  if (username == ''){
      document.getElementById("user-error").innerHTML = "Username must not be empty";
      return false;
  } else if(username != '') {    
    if( username.match(format)){
      document.getElementById("user-error").innerHTML = "Username must not contain any symbols";
      return false;
    }else if (username.length < 3){
      document.getElementById("user-error").innerHTML = "Username must contain at least 3 characters";
      return false;
    }else if (username.length > 10){
      document.getElementById("user-error").innerHTML = "Username must not exceed 10 characters";
      return false;
    }else{
      return true;
    }
  }
}
</script>

Here, we created an input field to insert username. We stored it in a variable named username and stored the HTML special characters that we want to exclude from the username in another variable named format.

The first thing we checked is the value. If no value is entered the function won't be triggered in this case but if the function was being triggered with a submit button then it would be needed. It will display an error message return false if there is no value, so no further blocks of javascript would run.

Then, we checked for the presence of special characters stored in format in the field. It will display an error message return false if there exist anyone of those, so no further blocks of javascript would run.

Then, we checked the minimum and miximum length of the value and made the script display error message in case it meets one of those conditions. If none of the validation conditions return true, the username will be valid and sent.

Types of Form Validation in Javascript

As stated earlier, form validation can be done in two ways. Lets have a look at both of them.

onchange() Validation

onchange() validation is useful when you want to validate each of the input fields as soon as a user enters some value into it. Both examples above are great examples of onchange vaidation.

Example

<input type="text" name="user" id="user_field" onChange="return userValidation()" placeholder="Username">

onsubmit() Validation

If you want to validate all the input fields at once after the user fills up the entire form fields, you can use onsubmit() validation. This can be done by adding an onsubmit event handler in the <form> tag or by aading an onclick() event handler to the submit button of the form.

Example

&lr;form method="POST" onsubmit="return formValidation()">
  // add input fields
  &lr;input type="submit" name="submit">
&lr;/form>

0 Like 0 Dislike 0 Comment Share

Leave a comment