Skip to main content

How to Add Form Validation on the Client-side using JavaScript

How to Create a Circular Scroll Progress with HTML, CSS & JavaScript

In this JavaScript guide, our focus will be on implementing client-side form validation using JavaScript. Additionally, we will explore two distinct input styles: success and error, which represent various states that inputs can assume.

Source Code

HTML

<div class="container">
	<div class="header">
		<h2>Create Account</h2>
	</div>
	<form id="form" class="form">
		<div class="form-control">
			<label for="username">Username</label>
			<input type="text" placeholder="florinpop17" id="username" />
			<i class="fas fa-check-circle"></i>
			<i class="fas fa-exclamation-circle"></i>
			<small>Error message</small>
		</div>
		<div class="form-control">
			<label for="username">Email</label>
			<input type="email" placeholder="a@florin-pop.com" id="email" />
			<i class="fas fa-check-circle"></i>
			<i class="fas fa-exclamation-circle"></i>
			<small>Error message</small>
		</div>
		<div class="form-control">
			<label for="username">Password</label>
			<input type="password" placeholder="Password" id="password"/>
			<i class="fas fa-check-circle"></i>
			<i class="fas fa-exclamation-circle"></i>
			<small>Error message</small>
		</div>
		<div class="form-control">
			<label for="username">Password check</label>
			<input type="password" placeholder="Password two" id="password2"/>
			<i class="fas fa-check-circle"></i>
			<i class="fas fa-exclamation-circle"></i>
			<small>Error message</small>
		</div>
		<button>Submit</button>
	</form>

</div>
CSS

@import url('https://fonts.googleapis.com/css?family=Muli&display=swap');
@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,500&display=swap');

* {
	box-sizing: border-box;
}

body {
	background-color: #9b59b6;
	font-family: 'Open Sans', sans-serif;
	display: flex;
	align-items: center;
	justify-content: center;
	min-height: 100vh;
	margin: 0;
}

.container {
	background-color: #fff;
	border-radius: 5px;
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
	overflow: hidden;
	width: 400px;
	max-width: 100%;
}

.header {
	border-bottom: 1px solid #f0f0f0;
	background-color: #f7f7f7;
	padding: 20px 40px;
}

.header h2 {
	margin: 0;
}

.form {
	padding: 30px 40px;	
}

.form-control {
	margin-bottom: 10px;
	padding-bottom: 20px;
	position: relative;
}

.form-control label {
	display: inline-block;
	margin-bottom: 5px;
}

.form-control input {
	border: 2px solid #f0f0f0;
	border-radius: 4px;
	display: block;
	font-family: inherit;
	font-size: 14px;
	padding: 10px;
	width: 100%;
}

.form-control input:focus {
	outline: 0;
	border-color: #777;
}

.form-control.success input {
	border-color: #2ecc71;
}

.form-control.error input {
	border-color: #e74c3c;
}

.form-control i {
	visibility: hidden;
	position: absolute;
	top: 40px;
	right: 10px;
}

.form-control.success i.fa-check-circle {
	color: #2ecc71;
	visibility: visible;
}

.form-control.error i.fa-exclamation-circle {
	color: #e74c3c;
	visibility: visible;
}

.form-control small {
	color: #e74c3c;
	position: absolute;
	bottom: 0;
	left: 0;
	visibility: hidden;
}

.form-control.error small {
	visibility: visible;
}

.form button {
	background-color: #8e44ad;
	border: 2px solid #8e44ad;
	border-radius: 4px;
	color: #fff;
	display: block;
	font-family: inherit;
	font-size: 16px;
	padding: 10px;
	margin-top: 20px;
	width: 100%;
}
JavaScript

const form = document.getElementById('form'); 
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');

form.addEventListener('submit', e => {
	e.preventDefault();
	
	checkInputs();
});

function checkInputs() {
	// trim to remove the whitespaces
	const usernameValue = username.value.trim();
	const emailValue = email.value.trim();
	const passwordValue = password.value.trim();
	const password2Value = password2.value.trim();
	
	if(usernameValue === '') {
		setErrorFor(username, 'Username cannot be blank');
	} else {
		setSuccessFor(username);
	}
	
	if(emailValue === '') {
		setErrorFor(email, 'Email cannot be blank');
	} else if (!isEmail(emailValue)) {
		setErrorFor(email, 'Not a valid email');
	} else {
		setSuccessFor(email);
	}
	
	if(passwordValue === '') {
		setErrorFor(password, 'Password cannot be blank');
	} else {
		setSuccessFor(password);
	}
	
	if(password2Value === '') {
		setErrorFor(password2, 'Password2 cannot be blank');
	} else if(passwordValue !== password2Value) {
		setErrorFor(password2, 'Passwords does not match');
	} else{
		setSuccessFor(password2);
	}
}

function setErrorFor(input, message) {
	const formControl = input.parentElement;
	const small = formControl.querySelector('small');
	formControl.className = 'form-control error';
	small.innerText = message;
}

function setSuccessFor(input) {
	const formControl = input.parentElement;
	formControl.className = 'form-control success';
}
	
function isEmail(email) {
	return /^(([^<>()\[\]\\.,;:\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,}))$/.test(email);
}

setErrorFor()

The setErrorFor() function is used to update appearance of a form control to indicate an error. It takes two parameters: input element and an error message. It starts by getting parent element of input and finding small element inside it. It then sets class of parent element to 'form-control error' to apply error style and sets inner text of small element to error message.

setSuccessFor()

This function is used to update appearance of a form control to indicate a successful input. It takes one parameter, input element. It starts by getting parent element of input and sets class of parent element to 'form-control success' to apply success style.

isEmail()

The isEmail() function that uses a regular expression pattern to check if input string is a valid email address. The regular expression pattern used in this function is quite complex, but it essentially checks if input string matches format of a valid email address. If input string matches format of a valid email address, function returns true. If input string does not match format of a valid email address, function returns false.

Comments

Popular posts from this blog

Everything You Need to Know About CSS Grid

Everything You Need to Know About CSS Grid We have a thorough manual on CSS grid, which covers all aspects of settings for both parent container and child elements of grid. Back to TOC Table of Contents Introduction Basics Important Terminology Grid Properties Special Units & Functions Fluid Columns Snippet Animation Introduction CSS Grid Layout, also known as "Grid" or "CSS Grid", is a revolutionary two-dimensional grid-based layout system that completely transforms the way we design user interfaces. In the past, CSS was used to layout web pages, but it was never very effective. We used tables, floats, positioning, and inline-...

Creating custom CSS shapes and icons

Creating Custom CSS Shapes and Icons Custom CSS shapes and icons refer to unique visual elements that are created using Cascading Style Sheets (CSS) rather than using traditional image formats such as JPEG, PNG, or SVG. By using CSS, developers can create custom shapes and icons that can be easily scaled, manipulated, and styled without having to rely on external image files. Back to TOC Table of Contents Introduction Creating Shapes with CSS Creating Icons with CSS Demo • Introduction In this article, we will learn how to create custom shapes and icons using CSS. We will explore different techniques and examples to help you understand how CSS can be used to create unique visual elements for your website. • Creating Shapes with CSS Creating custom shapes with CSS can be done using a variety of techniques such as using borders, gradients, and pseudo-...

Find Your Location using HTML, CSS & JavaScript

See the Pen Untitled by Mushtaq Ahmad ( @MushtaqPhysicist ) on CodePen . Find Your Location using HTML, CSS & JavaScript It is against policy to access Geolocation in Blogger.com . However, you can still find your location by clicking on CodePen button and then clicking the Get Location button to retrieve your location data Source Code HTML Copy Code <div class="container"> <h1>Find Your Location</h1> <p>Your location: <span id="location"></span></p> <button id="getLocation">Get Location</button> </div> CSS Copy Code body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #f5f5f5; } .container { max-width: 800px; margin: 0 auto; padding: 50px; background-color: #fff; border...