Form Validation using jQuery
Last Updated :
16 Sep, 2024
Form validation is a process of confirming the relevant information entered by the user in the input field. In this article, we will be validating a simple form that consists of a username, password, and a confirmed password using jQuery.
Below are the approaches for validation of form using jQuery:
Using plain jQuery
- First, you need to create an index.html file consisting of an HTML form with username, email, password, and confirm password as input fields.
- We will use Bootstrap 4 to use Bootstrap's form controls. At the bottom of the <body> tag, include the "app.js" file having jQuery code for form validation.
- Create an app.js file that validates the whole form as given below in the code.
- In the app.js file, when the document is ready, hide all the error messages.
- Perform the validation task for all the input fields such as username, email, password, and confirm password.
Example 1: This example illustrates the simple form validation using jQuery.
HTML
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Popper JS -->
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js">
</script>
<!-- Latest compiled JavaScript -->
<script src=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js">
</script>
</head>
<body>
<h1 class="text-center text-success">
Welcome to GeeksforGeeks
</h1>
<p class="text-center">
FORM VALIDATION USING JQUERY
</p>
<div class="container">
<div class="col-lg-8
m-auto d-block">
<form>
<div class="form-group">
<label for="user">
Username:
</label>
<input type="text"
name="username"
id="usernames"
class="form-control">
<h5 id="usercheck"
style="color: red;">
**Username is missing
</h5>
</div>
<div class="form-group">
<label for="user">
Email:
</label>
<input type="email"
name="email"
id="email" required
class="form-control">
<small id="emailvalid"
class="form-text text-muted invalid-feedback">
Your email must be a valid email
</small>
</div>
<div class="form-group">
<label for="password">
Password:
</label>
<input type="password"
name="pass"
id="password"
class="form-control">
<h5 id="passcheck"
style="color: red;">
**Please Fill the password
</h5>
</div>
<div class="form-group">
<label for="conpassword">
Confirm Password:
</label>
<input type="password"
name="username"
id="conpassword"
class="form-control">
<h5 id="conpasscheck"
style="color: red;">
**Password didn't match
</h5>
</div>
<input type="submit"
id="submitbtn"
value="Submit"
class="btn btn-primary">
</form>
</div>
</div>
<!-- Including app.js jQuery Script -->
<script src="app.js"></script>
</body>
</html>
JavaScript
$(document).ready(function () {
// Validate Username
$("#usercheck").hide();
let usernameError = true;
$("#usernames").keyup(function () {
validateUsername();
});
function validateUsername() {
let usernameValue = $("#usernames").val();
if (usernameValue.length === "") {
$("#usercheck").show();
usernameError = false;
return false;
} else if (usernameValue.length < 3 || usernameValue.length > 10) {
$("#usercheck").show();
$("#usercheck").html("**length of username must be between 3 and 10");
usernameError = false;
return false;
} else {
$("#usercheck").hide();
usernameError = true;
}
}
// Validate Email
const email = document.getElementById("email");
let emailError = true;
email.addEventListener("blur", () => {
let regex =
/^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
let s = email.value;
if (regex.test(s)) {
email.classList.remove("is-invalid");
emailError = true;
} else {
email.classList.add("is-invalid");
emailError = false;
}
});
// Validate Password
$("#passcheck").hide();
let passwordError = true;
$("#password").keyup(function () {
validatePassword();
});
function validatePassword() {
let passwordValue = $("#password").val();
if (passwordValue.length === "") {
$("#passcheck").show();
passwordError = false;
return false;
}
if (passwordValue.length < 3 || passwordValue.length > 10) {
$("#passcheck").show();
$("#passcheck").html(
"**length of your password must be between 3 and 10"
);
$("#passcheck").css("color", "red");
passwordError = false;
return false;
} else {
$("#passcheck").hide();
passwordError = true;
}
}
// Validate Confirm Password
$("#conpasscheck").hide();
let confirmPasswordError = true;
$("#conpassword").keyup(function () {
validateConfirmPassword();
});
function validateConfirmPassword() {
let confirmPasswordValue = $("#conpassword").val();
let passwordValue = $("#password").val();
if (passwordValue !== confirmPasswordValue) {
$("#conpasscheck").show();
$("#conpasscheck").html("**Password didn't Match");
$("#conpasscheck").css("color", "red");
confirmPasswordError = false;
return false;
} else {
$("#conpasscheck").hide();
confirmPasswordError = true;
}
}
// Submit button
$("#submitbtn").click(function () {
validateUsername();
validatePassword();
validateConfirmPassword();
email.dispatchEvent(new Event('blur'));
if (
usernameError &&
passwordError &&
confirmPasswordError &&
emailError
) {
return true;
} else {
return false;
}
});
});
Output:
aValidation using an inbuilt jQuery validation plugin
In this part, you get to know about the inbuilt validation method of jQuery. Create an index.html file and copy the following code.
Example : This example describes the form validation with the help of a built-in jQuery validation plugin.
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- below we are including the
jQuery and jQuery plugin .js files -->
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script src=
"https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js">
</script>
<script src=
"https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js">
</script>
</head>
<body>
<form class="cmxform"
id="commonForm"
method="get"
action="form-handler.html"
autocomplete="off">
<fieldset>
<legend>GFG Form</legend>
<p>
<label for="cname">
Name <span>(required at least 2 character)</span>
</label>
<!--User have to set the constraints
in attribute form-->
<input id="cname"
name="name"
minlength="2"
type="text" required>
</p>
<p>
<label for="cemail">
Email <span>(required, won't be published)</span>
</label>
<input id="cemail"
type="email"
name="email" required>
</p>
<p>
<label for="curl">
URL <span>(Optional)</span>
</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">
Your comment<span>(required)</span>
</label>
<textarea id="ccomment"
name="comment" required>
</textarea>
</p>
<p>
<input class="submit"
type="submit"
value="submit">
</p>
</fieldset>
</form>
</body>
</html>
JavaScript
// User have to use id for
// form and call validate method
$("#commonForm").validate();
Output:
jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for its philosophy of “Write less, do more".
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
Top 10 Projects For Beginners To Practice HTML and CSS Skills Learning to code is an exciting journey, especially when stepping into the world of programming with HTML and CSSâthe foundation of every website you see today. For most beginners, these two building blocks are the perfect starting point to explore the creative side of web development, designing vis
8 min read
Web Development Technologies Web development refers to building, creating, and maintaining websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet, i.e., websites.To better understand the foundation of web devel
7 min read