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

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

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

See the Pen How to Create a Circular Scroll Progress with HTML, CSS & JavaScript by Mushtaq Ahmad ( @MushtaqPhysicist ) on CodePen . How to Create a Circular Scroll Progress with HTML, CSS & JavaScript In this guide, we will explore process of using HTML, CSS, and JavaScript to design a circular scroll progress indicator. This type of indicator displays percentage of a webpage that has been scrolled. Specifically, we will create a circular indicator and position it in bottom right corner of webpage. The indicator's fill level will correspond to amount of page that has been scrolled. HTML Copy Code <!DOCTYPE html> <html lang="en"> <head> <title>Scroll Percentage</title> <!-- Stylesheet --> <link rel="stylesheet" href="style.css"> </head> <body>...

Develop a Quiz App with Timer using HTML CSS & JavaScript

Develop a Quiz App with Timer using HTML CSS & JavaScript See the Pen Create a Quiz App with Timer using HTML CSS & JavaScript by Mushtaq Ahmad ( @MushtaqPhysicist ) on CodePen . In this article you’ll learn how to Create a Quiz Application with Timer using HTML CSS & JavaScript. The Quiz App with Timer program consists of three layers or boxes that are sequentially displayed when a specific button is clicked. Initially, the webpage displays a "Start Quiz" button, which, upon clicking, triggers a pop-up animation displaying an info box. The info box contains the rules of the quiz and two buttons labeled "Exit" and "Continue." Clicking on the "Exit" button hides the info box, while clicking on "Continue" button displays the Quiz Box. Within the Quiz Box, there is a header with a title on the left side and a timer box on the right side. The timer starts at 15 seconds and decremen...