---
title: "How can you perform client-side form validation in JavaScript?"  
description: "Client-side form validation in JavaScript can be performed by adding event listeners to form elements"  
author: "Ravi Vishwakarma"  
published: 2024-06-17  
updated: 2024-06-18  
canonical: https://www.mindstick.com/blog/304377/how-can-you-perform-client-side-form-validation-in-javascript  
category: "javascript"  
tags: ["web development", "javascript", "front-end development"]  
reading_time: 4 minutes  

---

# How can you perform client-side form validation in JavaScript?

Client-side [form validation](https://www.mindstick.com/forum/158694/how-can-perform-form-validation-using-jquery) in JavaScript can be performed by adding [event listeners](https://www.mindstick.com/forum/159117/how-do-you-handle-events-using-jquery-and-attach-event-listeners-to-elements) to form elements and using JavaScript to check the values of form fields before submission. This can improve [user experience](https://www.mindstick.com/articles/12731/the-importance-of-feedback-to-the-user-experience) by providing immediate feedback and reducing the load on the server.

Here's a step-by-step guide on how to perform client-side form validation:

#### Basic Steps for Form Validation

1. **Get References to Form Elements**: Use JavaScript to reference the form and its elements.
2. **Add Event Listeners**: Attach event listeners to the form and its elements to handle user input and form submission.
3. **[Validate Input](https://www.mindstick.com/forum/158278/how-to-use-the-pattern-attribute-to-validate-input-fields-against-a-specific-regular-expression)**: Write validation functions to check the values of form fields.
4. **Provide Feedback**: Show [error messages](https://www.mindstick.com/forum/160245/how-to-customize-error-messages-with-a-data-annotation-in-asp-dot-net-core) or feedback to the user based on validation results.

## Example: Form Validation

## HTML Form

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

    <style type="text/css">
    	:root,
    	*{
    		font-size: large;
    	}
		form label.star,
		form label.required {
			content: '';
			font-weight: 500;
		}

		form label.star::after,
		form label.required::after {
			margin-left: 10px;
			content: '*';
			color: red;
		}
		input[type='password'] {
		  letter-spacing: 2px;
		}

	    .input-error {
	        color: red;
	        font-size: 0.9em;
	        font-weight: 500;
	        margin: 0.5rem auto;
	    }

    </style>

  </head>
  <body>
    <div class="container">
    	<div class="my-4">
    		<form id="myForm" class="row g-3" >
    			<div class="col-12">
    				<label for="username" class="form-label fw-bold star">
    					Username
    				</label>
    				<input class="form-control" placeholder="User Name" type="text" id="username" name="username"  />
    				<span id="usernameError" class="input-error"></span>
    			</div>
    			<div class="col-12">
			        <label for="email" class="form-label fw-bold star">Email</label>
        			<input class="form-control" placeholder="Email" type="text" id="email" name="email" />
        			<span id="emailError" class="input-error"></span>
    			</div>
    			<div class="col-12">
    				<label for="password" class="form-label fw-bold star">Password </label>
        			<input class="form-control" placeholder="********" type="password" id="password" name="password" />
        			<span id="passwordError" class="input-error"></span>
    			</div>
    			<div class="col-12">
    				<button class="btn btn-primary" type="submit">Submit</button>
    			</div>
    		</form>
    	</div>
    </div>
  </body>
</html>
```

## CSS For Error message

```css
.input-error {
	        color: red;
	        font-size: 0.9em;
	        font-weight: 500;
	        margin: 0.5rem auto;
	    }
```

## JavaScript for form validation

```javascript
  <script type="text/javascript">
  	document.addEventListener('DOMContentLoaded', function() {
  		var formData = null;
	    const form = document.getElementById('myForm');
	    const username = document.getElementById('username');
	    const email = document.getElementById('email');
	    const password = document.getElementById('password');
	    const usernameError = document.getElementById('usernameError');
	    const emailError = document.getElementById('emailError');
	    const passwordError = document.getElementById('passwordError');

	    form.addEventListener('submit', function(event) {

	        // Clear previous error messages
	        usernameError.textContent = '';
	        emailError.textContent = '';
	        passwordError.textContent = '';

	        // Validate each field
	        let isValid = true;

					if (username.value.trim().length < 3) {
					    usernameError.textContent = 'Username must be at least 3 characters long.';
					    isValid = false;
					    username.classList.add("is-invalid");
					} else {
					    // Clear any previous error message
					    usernameError.textContent = '';
					    // Remove the "is-invalid" class if username is valid
					    username.classList.remove("is-invalid");
					}

	        if (!validateEmail(email.value)) {
	            emailError.textContent = 'Please enter a valid email address. Like (xyx@gmail.com)';
	            isValid = false;
	        }

	        if (password.value.trim().length < 6) {
	            passwordError.textContent = 'Password must be at least 6 characters long.';
	            isValid = false;
	        }

					if (!isValid) {
					    event.preventDefault(); // Prevent form submission if validation fails
					}
	    });

		// Function to validate email using a simple regex
		function validateEmail(email) {
		    const re = /^[\w.-]+@[\w.-]+\.[\w]{2,}$/;
		    return re.test(email.toLowerCase());
		}

	});
```

## Output :

![How can you perform client-side form validation in JavaScript?](https://www.mindstick.com/blogs/61831ea1-8b58-42f3-b2fd-d58e2d3d301d/images/3a3702df-81cf-4e63-8a9e-49bbd8f6fc98.png)

####

#### Explanation

**HTML Form**:

- The form includes fields for username, email, and password.
- Each field has a corresponding `<span>` element to [display error](https://www.mindstick.com/forum/158286/how-to-display-error-messages-using-jquery-validation) messages.

**CSS for Error Messages** (optional):

- Error messages are styled in red to make them noticeable.

**JavaScript for Validation**:

- The JavaScript code is executed when the DOM content is loaded.
- References to form elements and error message containers are obtained using `getElementById`.
- An [event listener](https://www.mindstick.com/interview/529/how-to-remove-the-event-listener) is added to the form to handle the `submit` event.
- The `submit` [event handler](https://www.mindstick.com/forum/1371/c-sharp-dot-net-event-handler-delegate-question) function validates the form fields:

   1. It clears any previous error messages.
   2. It checks the length of the [username and password](https://www.mindstick.com/forum/160407/how-does-a-bearer-token-differ-from-other-authentication-methods-such-as-username-and-password), and validates the email format.
   3. If any [validation fails](https://www.mindstick.com/forum/34291/how-to-raise-a-callback-when-asp-dot-net-mvc-client-validation-fails), it sets the corresponding error message and prevents form submission by calling `event.preventDefault()`.

### Benefits of Client-Side Validation

- **Immediate Feedback**: Users get immediate feedback on their input, which improves user experience.
- **Reduced Server Load**: Reduces unnecessary server requests by catching invalid inputs early.
- **Enhanced User Experience**: Provides a more responsive and interactive form experience.

---

Original Source: https://www.mindstick.com/blog/304377/how-can-you-perform-client-side-form-validation-in-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
