Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
JavaScript Form Validation Examples
2.1.
HTML
3.
Importance of Form validation
4.
Types of JavaScript Form Validation
4.1.
1. JavaScript Number Validation
4.2.
HTML
4.3.
2. JavaScript Email Validation
4.4.
HTML
4.5.
3. JavaScript Password Text Validation
4.6.
HTML
4.7.
4. JavaScript Validation with Image
4.8.
HTML
5.
JavaScript Validation Table
6.
Frequently Asked Question
6.1.
How do I validate a form using JavaScript?
6.2.
How to submit form after JavaScript validation?
6.3.
Which of the following function is used to validate the form in JavaScript?
6.4.
How to invalidate form in JavaScript?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Javascript Form Validation

Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Hello Ninja, Welcome to the new article on Javascript Form Validation. Many times we need to fill out online forms over various platforms. For example, registration form, application form and survey form etc. So what if you want to gather information about people and you have created a form which includes mobile no, and in that field, some users misken by filling in some characters? To deal with this kind of situation, we need Javascript Form Validation.

Introduction

In this article, we will understand how to implement only a particular field type to the input, simply called From Validation.

Before going directly to form validation, we’ll explore input first.

JavaScript Form Validation Examples

Here's a simple example of JavaScript form validation, where we wish to check name must not be empty and the entered password must be at least 6 characters long.

Code

  • HTML

HTML

<form id="myForm">
<input type="text" id="name" placeholder="Name" required>
<input type="password" id="password" placeholder="Password" required>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
var nameInput = document.getElementById("name");
var passwordInput = document.getElementById("password");

if (nameInput.value === "" || passwordInput.value.length < 6) {
event.preventDefault();
alert("Name can't be empty and password must be at least 6 characters.");
}
});
</script>

Output

output
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Importance of Form validation

Form validation is very important for taking inputs from users. The first thing is it check that the data entered by the user is correct and can send to the backend or not. Sometimes what happens in the field of email some users do not include @. This can help to decrease the errors that can occur in the backend. Checking before sending the content into the backend help the logic to work correctly. The second thing is that form validation can help form hacking. Actually, what happens is that some hacker might write an injection into the input that will lead to a database breach. If a form is not validated correctly, it can be hacked by using such as SQL injection, cross-site scripting, etc. It is very important to check that the data entered by the user is the correct format.

  • Backend logic will work correctly.
     
  • Stop you from hacking from SQL injection and cross-site scripting.
     
  • Give you only correct information.

Types of JavaScript Form Validation

Now we will try to cover different types of form validation in javascript.

1. JavaScript Number Validation

Now we check if the entered data is a number or not. Here we will put an if condition to check whether the input is entered as a number. Check the code below.

Code

  • HTML

HTML

<!DOCTYPE html>
<html>
<body>
<h2>To check if input data is a number or not.</h2>
<p>Trying entering numbers between 1 to 100</p>
<input id="number1to10">
<button type="button" onclick="checkTheNumber()">Submit</button>

<h3 id="result"></h3>
<script>
function checkTheNumber() {
 // Here, we are taking the input field in the entered_value
 let entered_value = document.getElementById("number1to10").value;
 // If entered_value is not a number between 1 to 100
 let checkIfNumber;
 if (isNaN(entered_value) || entered_value < 1 || entered_value > 10) {
   checkIfNumber = "Input not valid";
 } else {
   checkIfNumber = "Input OK";
 }
 document.getElementById("result").innerHTML = text;
}
</script>

</body>
</html>

Output

This is the output of the correct input as a number.

Output

This is the output of incorrect input as an alphabet.

Output

2. JavaScript Email Validation

To check whether the data entered is email, we can implement it by setting type = “email”. So here, you can use the email attribute in the input tag assigned to the class. See the below example.

Code

  • HTML

HTML

<h2>Enter your email only. </h2>
<form >
 Email <input type="email"  required>
 <input type="submit" value="Submit">
</form>

Output

This is the output of the correct input as email.

Output

This is the output of incorrect input as regular text.

Output

3. JavaScript Password Text Validation

In the input field, everyone wants to hide and secure their password. So we can implement type = ”password”. So it will hide the text in the input field. Check out the below code.

Code

  • HTML

HTML

<h2>Enter your password only. </h2>
<form >
 Password <input type="password"  required>
 <input type="submit" value="Submit">
</form>

Output

Output

4. JavaScript Validation with Image

Here's to make it more interactive using images

Code

  • HTML

HTML

<script>
function validate() {
var name = document.form.name.value;
var password = document.form.password.value;
var nameElement = document.getElementById("name");
var passwordElement = document.getElementById("password");
var status = true;
if (name.length < 1) {
nameElement.innerHTML =
" <img class='image' src='https://cdn-icons-png.flaticon.com/512/169/169779.png'/> Please enter your name";
status = false;
} else {
nameElement.innerHTML =
" <img class='image' src='https://cdn-icons-png.flaticon.com/512/190/190411.png'/>";
}
if (password.length < 6) {
passwordElement.innerHTML =
" <img class='image' src='https://cdn-icons-png.flaticon.com/512/169/169779.png'/> Password must be at least 6 characters long";
status = false;
} else {
passwordElement.innerHTML =
" <img class='image' src='https://cdn-icons-png.flaticon.com/512/190/190411.png'/>";
}
return status;
}
</script>
<form name="form" onsubmit="return validate()">
<label>Name:</label>
<input type="text" name="name"/>
<span id="name"></span>
<br>
<label>Password:</label>
<input type="password" name="password"/>
<span id="password"></span>
<br>
<input type="submit" value="register"/>
</form>

Output

output

JavaScript Validation Table

Below is the table that shows where we can put validation in various fields.

Check Description
Required fields This will check if all the input fields are filled in.
Email address Check if the email address is valid.
Password Check if the password is at least eight characters long and contains at least one number.
Username Here you can check if the username is unique or not.
Password strength Check if the password is strong enough.
Date You can check if the date is valid.
Number Check if the number is a valid number.
Text Check if the text is valid text.
File Check if the file is a valid file type.

Now we discuss a very important FAQ related to Javascript Form Validation.

Frequently Asked Question

How do I validate a form using JavaScript?

To validate a form using JavaScript, attach a listener to the form's submit event. Access the form fields using their IDs, then apply your logic to see if it's correct. Use functions like event.preventDefault() to stop submission on errors.

How to submit form after JavaScript validation?

To submit a form after JavaScript validation, ensure the validation function returns `true`. To associate your custom validation function with the forms attribute, you can use "return validate()". If the validation is successful, the form submission proceeds, prevented otherwise. 

Which of the following function is used to validate the form in JavaScript?

In JavaScript developers typically create their custom functions for form validation. These functions are called when the form is submitted and are responsible for checking whether the entered data meets criteria. Usually these functions are triggered by the event "onsubmit". 

How to invalidate form in JavaScript?

To invalidate a form in JavaScript, set its `novalidate` attribute to prevent browser-based validation. This allows custom validation using JavaScript. Additionally, you can prevent form submission and show error messages based on your validation logic.

Conclusion

This article discusses JavaScript Form Validation, types, and also some of the important validation forms in the table format. It explains how we can put out the logic to any of the input fields we want. 

Refer to other related articles to improve your understanding of Form Validation  -

Happy Coding!

Previous article
How to Read *.CSV File in JavaScript?
Next article
isNaN() in JavaScript
Live masterclass