DEV Community

Cover image for Complete JavaScript Form Validation
Stackfindover
Stackfindover

Posted on • Updated on

Complete JavaScript Form Validation

Hello guys in this tutorial we will add validation in registration form using HTML CSS & JAVASCRIPT

First we need to create three files index.html ,Style.css and an JavaScript custom.js file then we need to do code for it.

Step:1

Add below code inside index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Form Validator</title>
    <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" />
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500&family=IBM+Plex+Serif:wght@300;400&display=swap" rel="stylesheet">
  </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">Password2</label>
          <input type="password" id="password2" placeholder="Enter Password Again">
          <small>Error message</small>
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
    <script src="custom.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step:2

Then we need to add code for style.css which code i provide in below screen.

:root {
  --success-color: #2ecc71;
  --error-color: #e74c3c;
}
* {
  box-sizing: border-box;
  font-family: 'IBM Plex Sans', serif; 
}
body {
  background-color: #f9fafb;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  margin: 0;
}
.container {
    background: #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;
    position: relative;
}
.form-control {
    padding-bottom: 10px;
    position: relative;
}
label {
    color: #777;
    display: block;
    margin-bottom: 5px;
}
input {
    border: 2px solid #f0f0f0;
    border-radius: 4px;
    display: block;
    width: 100%;
    padding: 10px;
    font-size: 15px;
}
input:focus {
    outline: 0;
    border-color: #777;
}
.form-control small {
    font-size: 12px;
    background: #fff;
    color: var(--error-color);
    position: absolute;
    left: 10px;
    bottom: 5px;
    visibility: hidden;
}
button {
    cursor: pointer;
    background: #3498db;
    border: 2px solid #3498db;
    border-radius: 4px;
    color: #fff;
    display: block;
    padding: 10px;
    margin-top: 20px;
    width: 100%;
    font-size: 16px;
}
.form:before,.form:after {
    content: "";
    top: 0;
    left: 0;
    right: 0;
    width: 100%;
    position: absolute;
    background: #3498db;
    height: 100%;
    z-index: -1;
    transform: skew(10deg, 10deg);
    filter: drop-shadow(2px 4px 6px rgba(0,0,0,0.3));
}
.form:after {
    transform: skew(-10deg, -10deg);
}
.form-control.error small {
    visibility: visible;
}
.form-control.error input {
  border-color: var(--error-color);
}
.form-control.success input {
  border-color: var(--success-color);
}
Enter fullscreen mode Exit fullscreen mode

Step:3

Then we need to add below code inside custom.js

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 input success
function ShowSuccess(input) {
  const formControl = input.parentElement;
  formControl.className = "form-control success";
}

//Check email
function CheckEmail(input) {
  const char = /^(([^<>()\[\]\\.,;:\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 (char.test(input.value.trim())) {
    ShowSuccess(input);
  }else {
    ShowError(input, "Email is not valid");
  }
}
function CheckRequired(inputErr) {
  inputErr.forEach(function(input){
    if (input.value.trim() === "") {
      ShowError(input, `${getFieldName(input)} is required`);
    }else {
      ShowSuccess(input);
    }
  });
}

function CheckLenght(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 then ${max} characters`);
  }else {
    ShowSuccess(input);
  }
}


function CheckPasswordsMatch(input1,input2) {
  if (input1.value !== input2.value) {
    ShowError(input2, "Password do not match");
  }
}

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

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

  CheckRequired([username, email, password, password2 ]);
  CheckLenght(username, 3, 15);
  CheckLenght(password, 8, 25);
  CheckEmail(email);
  CheckPasswordsMatch(password, password2);
});
Enter fullscreen mode Exit fullscreen mode

JavaScript Form Validation Video Output:

JavaScript Form Validation Codepen Output:

Discussion (2)

Collapse
pfacklam profile image
Paul Facklam

Good article! As an alternative I would like to propose another approach. You don't need Javascript at all. HTML input elements provide all you need:

  • a required attribute
  • a pattern attribute (e.g. for email validation)
  • an attribute for min, minlength, max and maxlength

These things are already available as browser funtionalities. How cool is this?

Collapse
stackfindover profile image
Stackfindover Author

Nice thanks