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

Styling SVGs with CSS

Styling SVGs with CSS SVGs are a versatile and powerful format for creating high-quality graphics on the web. However, by default, SVGs can appear plain and unstyled, which can make them feel out of place in a modern web design.That's where CSS comes in. By using CSS to style SVGs, you can add color, gradients, shadows, animations, and other visual effects that make them more dynamic and engaging. Back to TOC Table of Contents What is SVG? Inline vs External SVGs Basic Styling Techniques Advanced Styling Techniques Animation Demo • What is SVG? SVG stands for Scalable Vector Graphics. It is a vector graphics format that uses XML to define two-dimensional graphics. Unlike raster graphics, such as JPEGs or PNGs, SVGs can be scaled without losing quality, making them ideal for use on websites and other digital media. • Inline vs External SVGs SVGs can be...

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

CSS Glowing Corners Effects

CSS Glowing Corners Effects CSS glowing corners effects are a great way to add an extra touch of style to your website or app. By applying a subtle glowing effect to the corners of your elements, you can create a sense of depth and dimension that makes your design stand out. Back to TOC Table of Contents Introduction CSS Code Examples Conclusion Introduction CSS glowing corners effects are a popular way to add some style and visual interest to box elements on a webpage. With some simple CSS code, you can create a glowing effect around the corners of a box, which can be customized in terms of color, size, and intensity. In this article, we'll go over the basic CSS code for creating these effects, as well as some examples of how they can be used on a webpage. CSS Code The CSS code for creating glowing corners effects...