Client-Side Form Validation using JavaScript
Last Updated on August 28, 2023 by Editorial Team
Author(s): Vivek Chaudhary
Originally published on Towards AI.
The objective of this article is to learn how to perform form validations in JavaScript. For our learning purpose, I have designed an Employee Records Keeping website form using HTML, CSS, and JavaScript. All Form Validation logic is developed using JavaScript.
Below is the project Demo:
Project Development is divided into three steps:
- Writing the HTML
- Adding the CSS
- Writing the JavaScript
Write HTML to design the Form
<!--file name validations.html-->
<html>
<head>
</head>
<body>
<br>
<h2>Employee Record Keeping System</h2>
<div class=βcontainerβ>
<form id=βformβ onsubmit=βvalidation()β>
<div class=βtitleβ><b>Please Enter Values</b></div>
<! β First Name input β
<div>
<label for=βfnameβ>First Name</label>
<input
type=βtextβ
name=βfnameβ
id=βfnameβ
placeholder=βVivekβ/>
<p id=βerr1"></p>
</div>
<! β Last Name input β
<div>
<label for=βlnameβ>Last Name</label>
<input
type=βtextβ
name=βlnameβ
id=βlnameβ
placeholder=βChaudharyβ/>
<p id=βerr2"></p>
</div>
<! β EmployeeId input β
<div>
<label for=βeidβ>EmployeeId</label>
<input
type=βtextβ
name=βeidβ
id=βeidβ
placeholder=β1234"/>
<p id=βerr3"></p>
</div>
<! β Email input β
<div>
<label for=βemailβ>Email</label>
<input
type=βemailβ
name=βemailβ
id=βemailβ
placeholder=β[email protected]β/>
<p id=βerr4"></p>
</div>
<! β Department input β
<div>
<label for=βdidβ>DeptNo</label>
<input
type=βtextβ
name=βdidβ
id=βdidβ
placeholder=β10"/>
<p id=βerr5"></p>
</div>
<br><br>
<button id=βbtnβ type=βsubmitβ>Submit</button>
</form>
</div>
</body>
</html>
This is what form looks like at this point:
Done with the HTML.
Add CSS to style the form
CSS helps us to add some styling and effects to our form to help it look more attractive.
<style>
* {
margin: .5;
padding: .5;
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
form {
display: flex;
flex-direction: column;
justify-content: center;
max-width: 400px;
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
padding: 50px;
}
input[type=βtextβ],input[type=βemailβ]{
width: 100%;
border: 1px solid #333;
box-sizing: border-box
}
label {
display: block;
margin-bottom: 5px;
}
input:invalid{
box-shadow:0 0 5px 1px red;
}
input:focus {
border: 2px solid #f2796e;
}
form div input {
width: 100%;
height: 40px;
border-radius: 8px;
outline: none;
border: 2px solid #c4c4c4;
padding: 0 30px;
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}
form div {
position: relative;
margin-bottom: 15px;
}
input:focus {
border: 2px solid #f2796e;
}
button {
margin-top: 15px;
width: 100%;
height: 45px;
background-color: #6e98f2;
border: 2px solid #6e98f2;
border-radius: 8px;
color: #fff;
font-size: 20px;
cursor: pointer;
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
transition: all 0.1s ease;
}
.success-icon,
.failure-icon {
right: 0.5;
opacity: 0.5;
}
button:hover {
opacity: 0.7;
}
</style>
After adding CSS components to our HTML objects, this is how our form looks like.
Done with the styling.
Add JavaScript for Validations.
JavaScript helps us to access and modify DOM (Data Object Model) elements. I have broken the Javascript into several parts for better understanding.
Access HTML DOM elements via their IDs:
let fname=document.getElementById(βfnameβ);
let lname=document.getElementById(βlnameβ);
let eid=document.getElementById(βeidβ);
let email=document.getElementById(βemailβ);
let did=document.getElementById(βdidβ);
let form=document.getElementById(βformβ)
let err1=document.getElementById(βerr1β)
let err2=document.getElementById(βerr2β)
let err3=document.getElementById(βerr3β)
let err4=document.getElementById(βerr4β)
let err5=document.getElementById(βerr5β)
let successIcon = document.getElementsByClassName(βsuccess-iconβ)
let failureIcon = document.getElementsByClassName(βfailure-iconβ)
let deptno=[10,20,30,40,50]
let btn=document.getElementById("btn").type
getElementById() method is one of the most common methods in the HTML DOM. It is used access or modify an HTML element.
getElementByClassName() method returns a collection of elements with a specified class name(s).
we are using both methods to access the form components to modify their behaviour.
Define Regex for form components validation
// Javascript reGex for Name validation
var rName = /^[A-Za-z]+$/;
// Javascript reGex for EmpID validation.
var rEmpID=/\d{4}$/;
//Javascript reGex for Email Validation.
var rEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
//JS for deptno validation
var rDeptno = /^\d{2}$/;
Define a function for validation
//file name is validation.js
function validation() {
//first name validation
if (fname.value==ββ U+007CU+007C !fname.value.match(rName)){
err1.innerHTML=β*Firstname cannot be blank and should be charactersβ;
fname.style.border = β2px solid redβ;
}
else {
err1.innerHTML=ββ;
fname.style.border = β2px solid greenβ;
}
//last name validation
if (lname.value==ββ U+007CU+007C !lname.value.match(rName)){
err2.innerHTML=β*Lastname cannot be blank and should be in charactersβ;
lname.style.border = β2px solid redβ;
}
else {
err2.innerHTML=ββ;
lname.style.border = β2px solid greenβ;
}
//email validation
console.log(βemail id is β,email.value)
if (email.value==ββ && !rEmail.test(email.value)){
console.log(βinside email ifβ)
err4.innerHTML=β*EmailID should be non-empty and valid. Please follow rulesβ;
email.style.border = β2px solid redβ;
}
else {
err4.innerHTML=ββ;
email.style.border = β2px solid greenβ;
}
//employee ID validation
if (eid.value==ββ U+007CU+007C !rEmpID.test(eid.value)){
err3.innerHTML=β*Please enter a valid Employee ID starting with 2 characters and 6 digitsβ;
eid.style.border = β2px solid redβ;
}
else {
err3.innerHTML=ββ;
eid.style.border = β2px solid greenβ;
}
//department no validation
dept=Number(did.value)
console.log(βvalue of dept β,dept +β β+typeof(dept))
if (dept==ββ U+007CU+007C !rDeptno.test(dept)){
console.log(βinside ifβ)
err5.innerHTML=β*DeptNo cannot be Empty or non-numeric. Please check againβ;
did.style.border = β2px solid redβ;
}
else if(!dept==ββ && !deptno.includes(dept)) {
console.log(βvalue of dept entered β, did.value + β β+typeof(did.value))
err5.innerHTML=β*DeptNo should be from list of values[10,20,30,40].
Please check againβ;
did.style.border = β2px solid redβ;
}
else if(!dept==ββ && deptno.includes(dept)){
console.log(βinside 2nd elifβ)
err5.innerHTML=ββ;
did.style.border = β2px solid greenβ;
}
}
form.addEventListener(btn,(event)=>{
event.preventDefault()
});
Validations
- FirstName
let fname=document.getElementById(βfnameβ);
let err1=document.getElementById("err1");
// Javascript reGex for Name validation
var rName = /^[A-Za-z]+$/;
//first name validation
if (fname.value=="" U+007CU+007C !fname.value.match(rName)){
err1.innerHTML="*Firstname cannot be blank and should be in characters";
fname.style.border = "2px solid red";
}
else {
err1.innerHTML="";
fname.style.border = "2px solid green";
}
- access the form input item of text type for firstname using document.getElementById(βfnameβ) also accesses the error tag using document.getElementById(βerr1β)
- define a regex expression for firstname using rName = /^[A-Za-z]+$/
- next part is the if-else block, where the comparison is made to take action on form. if firstname entered by the user is null or doesn't satisfy the regex criteria, the text field will be marked red with an error message.
- when first name entered by user satisfy the policy then result is as below, text field is marked as green.
LastName validation logic is the same as FirstName.
2. Email
let email=document.getElementById(βemailβ);
let err4=document.getElementById("err4");
//Javascript reGex for Email Validation.
var rEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
//email validation
if (email.value=="" && !rEmail.test(email.value)){
err4.innerHTML="*EmailID should be non-empty and valid. Please follow rules";
email.style.border = "2px solid red";
}
else {
err4.innerHTML="";
email.style.border = "2px solid green";
}
- access the form input item of text type for email using document.getElementById(βemailβ) also access the error tag using document.getElementById(βerr4β).
- if emailID entered by the user is Null or does not satisfy regex criteria, the text field will be marked red with an error message.
- as we have defined the text input field as email type it expects β@β symbol or else it will throw an error as below:
- when the email entered by the user satisfies the policy, then the result is as below: text field is marked as green.
3. DeptNo
let did=document.getElementById(βdidβ);
let err5=document.getElementById("err5")
//list of values for departments
let deptno=[10,20,30,40,50]
//department no validation
dept=Number(did.value)
if (dept=="" U+007CU+007C !rDeptno.test(dept)){
console.log('inside if')
err5.innerHTML="*DeptNo cannot be Empty or non-numeric. Please check again";
did.style.border = "2px solid red";
}
else if(!dept=="" && !deptno.includes(dept)) {
err5.innerHTML="*DeptNo should be from list of values[10,20,30,40].
Please check again";
did.style.border = "2px solid red";
}
else if(!dept=="" && deptno.includes(dept)){
err5.innerHTML="";
did.style.border = "2px solid green";
}
}
- access the form input item of text type for email using document.getElementById(βdidβ) Also access the error tag using document.getElementById(βerr5β).
- if values entered by the user doesnβt satisfy the if condition, then an error is thrown, and the text field is marked as red.
- if values entered by the user donβt satisfy the else if condition, then an error is thrown, and the text field is marked as red.
- if values entered by the user satisfy the else if condition, then the text field is marked as green.
Thatβs all with the Form Validation logic written in JavaScript.
Results If all inputs given by the user are incorrect:
Results If all inputs given by the user are correct:
The scope of this article is related to client-side validations only.
Summary:
- write HTML to define the project form.
- add CSS to style the HTML form elements.
- JavaScript to handle the form validation on the client side.
Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming aΒ sponsor.
Published via Towards AI