Form Validation Using HTML, CSS, and JavaScript
Published: 2023-05-19 05:01:41

Hello Coder! Welcome To The Codewithrandom Blog. In This Blog, We Learn How To Write A Program Of **[Form Validation](https://www.codewithrandom.com/2023/04/21/form-validator-javascript-form-validator-using-html-css-javascript/)** 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.

## 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.
```
<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.

## 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.
```
@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. 

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.
```
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 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](https://www.codewithrandom.com/2023/04/21/form-validator-javascript-form-validator-using-html-css-javascript/)** 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