Form Validator using JavaScript, HTML and CSS

In this tutorial, we will guide you through creating a simple client-side form validator. This project is an excellent start for beginners looking to understand form validation on the web. You will learn how to validate required fields, check input lengths, validate emails using regular expressions, and ensure password fields match. 

Project Specifications

Create a form UI: Design the user interface for the form.

Display error messages: Show feedback for incorrect inputs directly under the form fields.

Field Validations: Implement functions to validate inputs: 
  • checkRequired() for mandatory fields. 
  • checkLength() for input length constraints.
  • checkEmail() for email format validation.
  • checkPasswordsMatch() to ensure password fields match.

Setting Up the Project

Create a folder named form-validator as your workspace. Inside this folder, create three files: index.html, style.css, and script.js.

1. index.html

Structure the form with HTML, providing input fields for username, email, password, and password confirmation. Link to the CSS file for styling.

Let's create index.html and add the following code to it:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <title>Form Validator</title>
  </head>
  <body>
    <div class="container">
      <form id="form" class="form">
        <h2>Register With Us</h2>
        <div class="form-control">
          <label for="username">Username</label>
          <input type="text" id="username" placeholder="Enter username" />
          <small>Error message</small>
        </div>
        <div class="form-control">
          <label for="email">Email</label>
          <input type="text" id="email" placeholder="Enter email" />
          <small>Error message</small>
        </div>
        <div class="form-control">
          <label for="password">Password</label>
          <input type="password" id="password" placeholder="Enter password" />
          <small>Error message</small>
        </div>
        <div class="form-control">
          <label for="password2">Confirm Password</label>
          <input
            type="password"
            id="password2"
            placeholder="Enter password again"
          />
          <small>Error message</small>
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>

    <script src="script.js"></script>
  </body>
</html>

2. script.js 

Let's create a JavaScript file named script.js and add the following JavaScript code to it:
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');

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

// Show success outline
function showSuccess(input) {
  const formControl = input.parentElement;
  formControl.className = 'form-control success';
}

// Check email 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, 'Email is not valid');
  }
}

// Check required fields
function checkRequired(inputArr) {
  let isRequired = false;
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      showError(input, `${getFieldName(input)} is required`);
      isRequired = true;
    } else {
      showSuccess(input);
    }
  });

  return isRequired;
}

// Check input length
function checkLength(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 passwords match
function checkPasswordsMatch(input1, input2) {
  if (input1.value !== input2.value) {
    showError(input2, 'Passwords do not match');
  }
}

// Get fieldname
function getFieldName(input) {
  return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}

// Event listeners
form.addEventListener('submit', function(e) {
  e.preventDefault();

  if(!checkRequired([username, email, password, password2])){
    checkLength(username, 3, 15);
    checkLength(password, 6, 25);
    checkEmail(email);
    checkPasswordsMatch(password, password2);
  }
});

Validation Functions: 

showError() and showSuccess() to provide visual feedback. 
checkEmail() uses a regular expression to validate the email format. 
checkRequired() iterates over an array of inputs to ensure they are filled out.
checkLength() verifies if an input's value length is within specified bounds. 
checkPasswordsMatch() compares two password fields. 

Event Listeners: 

Use form.addEventListener('submit', callback) to validate inputs when the form is submitted. 

Explanation of Key JavaScript Functions: 

showError(input, message): This function takes an input element and a message string as arguments. It visually indicates an error state on the input and displays the message. 

showSuccess(input): Opposite to showError, this function indicates a successful validation of the input. 

Regular Expression for Email Validation: The checkEmail function uses a regular expression to test if the email input matches a valid email format. This is a common approach in form validation to ensure user input conforms to expected patterns. 

Field Validation Logic: We implement the core validation logic through checkRequired, checkLength, and checkPasswordsMatch. These functions provide immediate feedback to the user, which is crucial for a good user experience. 

style.css

Use CSS to style the form, focusing on visual feedback for validation states like success and error. Highlight input fields and display error messages appropriately. 

Let's create a CSS file named style.css and add the following CSS code to it:
@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');

:root {
  --success-color: #2ecc71;
  --error-color: #e74c3c;
}

* {
  box-sizing: border-box;
}

body {
  background-color: #f9fafb;
  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 10px rgba(0, 0, 0, 0.3);
  width: 400px;
}

h2 {
  text-align: center;
  margin: 0 0 20px;
}

.form {
  padding: 30px 40px;
}

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

.form-control label {
  color: #777;
  display: block;
  margin-bottom: 5px;
}

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

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

.form-control.success input {
  border-color: var(--success-color);
}

.form-control.error input {
  border-color: var(--error-color);
}

.form-control small {
  color: var(--error-color);
  position: absolute;
  bottom: 0;
  left: 0;
  visibility: hidden;
}

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

.form button {
  cursor: pointer;
  background-color: #3498db;
  border: 2px solid #3498db;
  border-radius: 4px;
  color: #fff;
  display: block;
  font-size: 16px;
  padding: 10px;
  margin-top: 20px;
  width: 100%;
}

Open index.html in Browser 

Let's open the index.html file in the browser, and you will be able to see the following screen:

Comments