Form Validation Using HTML, CSS, and JavaScript

 

Form Validation Using HTML, CSS, and JavaScript
Form Validator Using HTML, CSS, and JavaScript

Hello Coder! Welcome To The Codewithrandom Blog. In This Blog, We Learn How To Write A Program Of Form Validation By Using Html And Javascript. We Validate Passwords, Confirm Passwords, And Email Id Using JavaScript.

I Hope You Enjoy Our Blog So Let’s Start With A Basic Html Structure For Form Validation.

Preview of the project

Project NameForm Validator
Code By & Written ByCode With Random/Anki 
Project DownloadCopy Code From Given Code Snippets And Codepen Embed
Language UsedHTML, CSS, And JavaScript
External Link / DependenciesNo
ResponsiveYes
Form Validation project information


How to make form validation using HTML, CSS, and JavaScript?

HTML Code:-

  • In the HTML code we have a parent div, which has class name “Container“. Under this div we have a heading with H1 tag, the we have a form element to create the form, This form has a ID and class name with same name “Form”.
  • in the form element we have input elements for username, email, password and confirm-password. we give a unique id name to every inputs.
  • Also we have a button element for submit the form. copy all the HTML code and paste these in your HTML file.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<body>
<div class="container">
<h1>Register With Us</h1>
<form action="" id="form" class="form">
<div class="input">
<label for="username">Username</label>
<input
type="text"
name="username"
id="username"
placeholder="Username"
autocomplete="off"
/>
<small>Error message</small>
</div>
<div class="input">
<label for="email">Email</label>
<input
type="text"
name="email"
id="email"
placeholder="Email"
autocomplete="off"
/>
<small>Error message</small>
</div>
<div class="input">
<label for="password">Password</label>
<input
type="password"
name="password"
id="password"
placeholder="Password"
/>
<small>Error message</small>
</div>
<div class="input">
<label for="c-password">Confirmer Password</label>
<input
type="password"
name="c-password"
id="c-password"
placeholder="Confirmer Password"
/>
<small>Error message</small>
</div>
<button>Submit</button>
</form>
</div>
</body>
<body> <div class="container"> <h1>Register With Us</h1> <form action="" id="form" class="form"> <div class="input"> <label for="username">Username</label> <input type="text" name="username" id="username" placeholder="Username" autocomplete="off" /> <small>Error message</small> </div> <div class="input"> <label for="email">Email</label> <input type="text" name="email" id="email" placeholder="Email" autocomplete="off" /> <small>Error message</small> </div> <div class="input"> <label for="password">Password</label> <input type="password" name="password" id="password" placeholder="Password" /> <small>Error message</small> </div> <div class="input"> <label for="c-password">Confirmer Password</label> <input type="password" name="c-password" id="c-password" placeholder="Confirmer Password" /> <small>Error message</small> </div> <button>Submit</button> </form> </div> </body>
<body>
<div class="container">
<h1>Register With Us</h1>
<form action="" id="form" class="form">
<div class="input">
<label for="username">Username</label>
<input
type="text"
name="username"
id="username"
placeholder="Username"
autocomplete="off"
/>
<small>Error message</small>
</div>
<div class="input">
<label for="email">Email</label>
<input
type="text"
name="email"
id="email"
placeholder="Email"
autocomplete="off"
/>
<small>Error message</small>
</div>
<div class="input">
<label for="password">Password</label>
<input
type="password"
name="password"
id="password"
placeholder="Password"
/>
<small>Error message</small>
</div>
<div class="input">
<label for="c-password">Confirmer Password</label>
<input
type="password"
name="c-password"
id="c-password"
placeholder="Confirmer Password"
/>
<small>Error message</small>
</div>
<button>Submit</button>
</form>
</div>
</body>

There Is All The Html Code of the project. Now, You Can See Output Without Css And JavaScript. Then We Write Css To The Style Form Element And Design it And Use JavaScript For Password Validation And Email Validation.

Read also: Portfolio Website using HTML and CSS (Source Code)

Html Code Output:-

 

Form Validation Using HTML, CSS, and JavaScript
 

CSS Code For Form Validator:-

  • In this CSS we give style all the elements and give proper padding, color, margin and better looks. Also we have import the google font in CSS.
  • copy all the CSS code and paste all these into your CSS file.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@import url("https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: none;
}
body {
background-color: #f9fafb;
font-family: "Open Sans", sans-serif;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
width: 400px;
padding: 30px 40px;
}
.container h1 {
text-align: center;
margin: 0 0 20px;
font-size: 24px;
}
.input {
margin-bottom: 20px;
position: relative;
}
.input label {
display: block;
margin-bottom: 10px;
}
.input input {
width: 100%;
height: 40px;
padding: 0 15px;
background-color: transparent;
border: 2px solid #f0f0f0;
border-radius: 5px;
}
.input small {
display: block;
color: #e74c3c;
font-weight: bold;
font-size: 11px;
padding-top: 3px;
visibility: hidden;
}
.input.success input {
border: 2px solid #2ecc71;
}
.input.error input {
border: 2px solid #e74c3c;
}
.input.error small {
visibility: visible;
}
button {
width: 100%;
height: 40px;
line-height: 40px;
background-color: #3498db;
border: 1px solid #3498db;
border-radius: 5px;
cursor: pointer;
color: #fff;
display: block;
font-size: 16px;
}
@import url("https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap"); * { margin: 0; padding: 0; box-sizing: border-box; outline: none; } body { background-color: #f9fafb; font-family: "Open Sans", sans-serif; height: 100vh; display: flex; align-items: center; justify-content: center; } .container { background-color: #fff; border-radius: 5px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); width: 400px; padding: 30px 40px; } .container h1 { text-align: center; margin: 0 0 20px; font-size: 24px; } .input { margin-bottom: 20px; position: relative; } .input label { display: block; margin-bottom: 10px; } .input input { width: 100%; height: 40px; padding: 0 15px; background-color: transparent; border: 2px solid #f0f0f0; border-radius: 5px; } .input small { display: block; color: #e74c3c; font-weight: bold; font-size: 11px; padding-top: 3px; visibility: hidden; } .input.success input { border: 2px solid #2ecc71; } .input.error input { border: 2px solid #e74c3c; } .input.error small { visibility: visible; } button { width: 100%; height: 40px; line-height: 40px; background-color: #3498db; border: 1px solid #3498db; border-radius: 5px; cursor: pointer; color: #fff; display: block; font-size: 16px; }
@import url("https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
outline: none;
}
body {
background-color: #f9fafb;
font-family: "Open Sans", sans-serif;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
background-color: #fff;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
width: 400px;
padding: 30px 40px;
}
.container h1 {
text-align: center;
margin: 0 0 20px;
font-size: 24px;
}
.input {
margin-bottom: 20px;
position: relative;
}
.input label {
display: block;
margin-bottom: 10px;
}
.input input {
width: 100%;
height: 40px;
padding: 0 15px;
background-color: transparent;
border: 2px solid #f0f0f0;
border-radius: 5px;
}
.input small {
display: block;
color: #e74c3c;
font-weight: bold;
font-size: 11px;
padding-top: 3px;
visibility: hidden;
}
.input.success input {
border: 2px solid #2ecc71;
}
.input.error input {
border: 2px solid #e74c3c;
}
.input.error small {
visibility: visible;
}
button {
width: 100%;
height: 40px;
line-height: 40px;
background-color: #3498db;
border: 1px solid #3498db;
border-radius: 5px;
cursor: pointer;
color: #fff;
display: block;
font-size: 16px;
}


Now we have completed our Css Code For Form Styling. 

Html + Css Code Output:-

 

Form Validation Using HTML,CSS and JavaScript
 

 


Now add javascript code and give validation in the form.

JavaScript Code For Form Validator:-

  • In the javaScript code we have created function, logic to create validation fuctionality in form. We get all the inputs by const variables and we created logic on these inputs and submit button.
  • Basicaly we use if, else statement in javascript for checking condition.
  • Alright, now just look on javaScript code and paste into your javascript file.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const form = document.getElementById("form");
const username = document.getElementById("username");
const email = document.getElementById("email");
const password = document.getElementById("password");
const cPassword = document.getElementById("c-password");
//Show Error Message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = "input error";
const small = formControl.querySelector("small");
small.innerText = message;
}
//Show Success message
function showSuccess(input) {
const formControl = input.parentElement;
formControl.classList.add("success");
}
//Check Required fields
function checkRequired(inputArr) {
inputArr.forEach(function (input) {
if (input.value.trim() === "") {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get Field Name
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Check Input Lenght
function checkLenghth(input, min, max) {
if (input.value.length < min) {
showError(
input,
`${getFieldName(input)} must be at least ${min} characters `
);
} else if (input.value.length > max) {
showError(
input,
`${getFieldName(input)} must be less than ${max} characters `
);
} else {
showSuccess(input);
}
}
// Check E-mail Is Valid
function checkEmail(input) {
const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input);
} else {
showError(input, "E-mail is not Valid");
}
}
// Check Password Match
function checkPasswordMatch(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, "Passwords do not match");
}
}
form.addEventListener("submit", (e) => {
e.preventDefault();
checkRequired([username, email, password, cPassword]);
checkLenghth(username, 3, 15);
checkLenghth(password, 8, 25);
checkEmail(email);
checkPasswordMatch(password, cPassword);
});
const form = document.getElementById("form"); const username = document.getElementById("username"); const email = document.getElementById("email"); const password = document.getElementById("password"); const cPassword = document.getElementById("c-password"); //Show Error Message function showError(input, message) { const formControl = input.parentElement; formControl.className = "input error"; const small = formControl.querySelector("small"); small.innerText = message; } //Show Success message function showSuccess(input) { const formControl = input.parentElement; formControl.classList.add("success"); } //Check Required fields function checkRequired(inputArr) { inputArr.forEach(function (input) { if (input.value.trim() === "") { showError(input, `${getFieldName(input)} is required`); } else { showSuccess(input); } }); } // Get Field Name function getFieldName(input) { return input.id.charAt(0).toUpperCase() + input.id.slice(1); } // Check Input Lenght function checkLenghth(input, min, max) { if (input.value.length < min) { showError( input, `${getFieldName(input)} must be at least ${min} characters ` ); } else if (input.value.length > max) { showError( input, `${getFieldName(input)} must be less than ${max} characters ` ); } else { showSuccess(input); } } // Check E-mail Is Valid function checkEmail(input) { const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/; if (re.test(input.value.trim())) { showSuccess(input); } else { showError(input, "E-mail is not Valid"); } } // Check Password Match function checkPasswordMatch(input1, input2) { if (input1.value !== input2.value) { showError(input2, "Passwords do not match"); } } form.addEventListener("submit", (e) => { e.preventDefault(); checkRequired([username, email, password, cPassword]); checkLenghth(username, 3, 15); checkLenghth(password, 8, 25); checkEmail(email); checkPasswordMatch(password, cPassword); });
const form = document.getElementById("form");
const username = document.getElementById("username");
const email = document.getElementById("email");
const password = document.getElementById("password");
const cPassword = document.getElementById("c-password");
//Show Error Message
function showError(input, message) {
const formControl = input.parentElement;
formControl.className = "input error";
const small = formControl.querySelector("small");
small.innerText = message;
}
//Show Success message
function showSuccess(input) {
const formControl = input.parentElement;
formControl.classList.add("success");
}
//Check Required fields
function checkRequired(inputArr) {
inputArr.forEach(function (input) {
if (input.value.trim() === "") {
showError(input, `${getFieldName(input)} is required`);
} else {
showSuccess(input);
}
});
}
// Get Field Name
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Check Input Lenght
function checkLenghth(input, min, max) {
if (input.value.length < min) {
showError(
input,
`${getFieldName(input)} must be at least ${min} characters `
);
} else if (input.value.length > max) {
showError(
input,
`${getFieldName(input)} must be less than ${max} characters `
);
} else {
showSuccess(input);
}
}
// Check E-mail Is Valid
function checkEmail(input) {
const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input);
} else {
showError(input, "E-mail is not Valid");
}
}
// Check Password Match
function checkPasswordMatch(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, "Passwords do not match");
}
}
form.addEventListener("submit", (e) => {
e.preventDefault();
checkRequired([username, email, password, cPassword]);
checkLenghth(username, 3, 15);
checkLenghth(password, 8, 25);
checkEmail(email);
checkPasswordMatch(password, cPassword);
});

Now we complete our all code for form validation, Now time to see Final Output!

Final Output Of Form Validation Using Html Css And Javascript:-

Form Validation Using HTML,CSS and JavaScript
Form Validation Using HTML,CSS and JavaScript

Read also:


Now We Have Completed Our Form Validation Using Html Css And Javascript. Hope You Like Form Validation. You Can See The Output Video And Project Screenshots. See Our Other Blogs And Gain Knowledge In Front-End Development.

Thank You!

In This Post, We Learn How To Create a Form Validation Using HTML, CSS, And JavaScript. If We Made A Mistake Or Any Confusion, Please Drop A Comment To Reply Or Help You In Easy Learning.

Written By – Code With Random/Anki 

How to make form validation using HTML, CSS, and JavaScript?

In the HTML code we have a parent div, which has class name “Container“. Under this div we have a heading with H1 tag, the we have a form element to create the form, This form has a ID and class name with same name “Form”.

in the form element we have input elements for username, email, password and confirm-password. we give a unique id name to every inputs.

Form Validator Using HTML, CSS, and JavaScript

In The HTML Code We Have A Parent Div, Which Has Class Name “Container“. Under This Div We Have A Heading With H1 Tag, The We Have A Form Element To Create The Form, This Form Has A ID And Class Name With Same Name “Form”

Previous Post Next Post