JavaScript Form Validation

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!
Learn via video course
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
By Mrinal Bhattacharya
Free
4.8
Enrolled: 1000
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
Mrinal Bhattacharya
Free
4.8
Enrolled: 1000
Start Learning

Overview

A form validation process verifies the information provided by the user before it is sent to the backend server. By verifying data, we eliminate unnecessary bugs, unhandled hindrances on the server, and API crashing due to unresponsiveness.

Introduction

Generally, forms are used to collect data from users. Data is sent to the backend when it is received from the user. However, what if the data is formatted incorrectly or if it does not comply with the server's recommendation? When such situations occur, the server might not respond as expected. In conclusion, we should validate the data before moving forward with the functionality of the server API. A point to note is that user data is sent to the server through the Request Object, and this takes some time. As a result, verifying the data on the server and sending a response if it is incorrect would be a lengthy process. The concept of client-side validation with javascript evolved from there to enhance the performance.

In real-world applications, validation happens on both sides, i.e., on the server side and on the user side.

A particular aspect of validation in Javascript will be discussed in this section, and that is forms. An example from real life will help us to understand the situation. As you might have filled out a lot of forms on the web applications, let's say you are trying to login into the application and you entered the incorrect email address or you did not provide a password, then you will be given an error message that the email is invalid or the password field is empty. All of these kinds of validations are performed by Javascript.

Building the Form Validation Script

Scripts are small pieces of code written in Javascript either in a script tag or in a separate file for some short automated process. With the Javascript form validation script, we can validate several input fields to ensure that user data is authentic. The script specifies when a request is to be sent to the server, obviously after the validations of user data.

JavaScript Form Validation Examples

In this example, we will check for several form input fields like,

  • Name should neither be null or blank nor consists of less than 3 characters.
  • Password should neither be null or blank nor consists of less than 6 characters. Also, both passwords must match.
  • Image must be of gif, png, or jpeg extension.
  • Phone Number must contain all numeric values.
  • Email must be correct(Further explanation of provided regex is given below).

JavaScript Name Validation

This javascript function will accept a name variable and will check whether it is null or blank, subsequently, it will check for the length of the name, which should not be less than 3.

JavaScript Re-Type Password Validation

This javascript function will compare the two provided passwords.

JavaScript Number Validation

This function will check whether the given input is a number or not. In javascript, we have an inbuilt function isNaN() which returns true if the provided argument is a number.

JavaScript Validation for Image

This function will accept the path of the image file, which is provided by the value attribute of HTML. In this function, we are splitting the path at the \ character, and the pop function is returning the last element of the array after the split. In this way, we are somehow getting the file name. Later we have a Regex pattern which will be used to check whether there is .jpg, .jpeg, or .png in the file name, exec() method is being used for the same purpose.

Example:

If we combine all the functions described above with our HTML form, it will look something like this.

Note : We are not showing the CSS file just to avoid the length of code because this article is not concerned with styling.

Explanation:

  • We are performing the execution of validateForm() function with the submit button of the form.
  • Inside the validateForm() we are accessing the node of the document by their name attribute to ultimately fetch their value.
  • Example : document.signup.fname.value, It will look for the signup named node which is a form, and then it will look for the fname named child which is an input element and finally it will access the value.
  • We are maintaining a boolean variable namedisValid according to return values of validation functions.
  • At the end, if our isValid variable contains false then the form is not valid to be submitted.

JavaScript Email Validation

This function will accept an email string as a parameter and test it against a regex pattern to ensure that provided string is a valid email. Below is the description of RegExp Pattern,

  • ^ denotes the starting of the string.
  • [a-zA-Z0-9_.] denotes that characters from a-z, A-Z, 0-9, and _ are allowed.
  • + denotes that the previous pattern could occur one or several times.
  • @ will check for an exact match.
  • [a-zA-Z0-9.] again it will check for a-z, A-Z, 0-9, and ..
  • + denotes that the previous pattern could occur one or several times and subsequent $ denotes the end of the Pattern.

Understanding Client-Side Validation

Client-side validation protects our server against inappropriate data before a request is sent to the server. This initial validation check provides a better user experience by avoiding the lengthy process of validation at the server only. We can validate the data entered by the user, like ensuring the input format is correct, the mandatory fields are filled in, etc. By implementing client-side validation, we can determine when a request should be sent to the server. Client Side Validation

Creating the HTML Form

We can create an HTML form by using the HTML tags related to forms, like, form, input, etc.

This is what a basic form looks like in javascript.

Let's try to transform this into a dummy sign-up form.

Output:

When we open this HTML file in our browser we would be able to see this form as output,

HTML form creation

Adding Style Sheet to Beautify the Form

CSS File:

Output:

Our styled form will look something like this,

Sign Up Form Output

Conclusion

  • Client-side validations are performed in order to protect our server from invalid data.
  • A server cannot respond correctly if the incoming data is not well-formatted; it is, therefore, necessary to validate the data.
  • In Javascript, we can validate a form by writing a script and then attaching the script to the submit button's on-click event.
  • If the script can determine the validity of the data, then only the server requests will be executed.