paint-brush
Validate Form Inputs with HTML, CSS and JavaScriptby@taimoorsaddique
3,032 reads
3,032 reads

Validate Form Inputs with HTML, CSS and JavaScript

by Taimoor SaddiqueMarch 19th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Form validation is a way of making your form input secure by not letting any malicious code in your website. Form validation restricts a user by processing the input in your desired way. A form without proper validation is like an open door for attackers, and your precious data could be at risk. A website with proper form validation helps prevent a lot of attacks like ***[cross-site scripting](https://en.wikipedia.org/wiki/Cross-site_scripting)***, ***[SQL injection]***, etc. These attacks are very common and they can harm the privacy of your users.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Validate Form Inputs with HTML, CSS and JavaScript
Taimoor Saddique HackerNoon profile picture

What is form validation?

Form validation is a way of making your form input secure by not letting any malicious code in your website. Form validation restricts a user by processing the input in your desired way. This means that if you have an input that asks for the user’s name and your user enters a malicious code. If you don’t check what the user has entered then this would create problems for you. This happens a lot and sometimes users do it intentionally. To prevent that, you have to check every input whether a user has entered correct information or not.

Importance of form validation

The most vulnerable part of a website is the form. Attackers can manipulate the whole website by using a simple form input. In order to prevent malicious attacks on your website, you need to develop strategies to secure the input and make your forms less vulnerable, and you can do this by proper form validation. A form without proper validation is like an open door for attackers, and your precious data could be at risk.

A website with proper form validation helps prevent a lot of attacks like cross-site scripting, SQL injection, etc. These attacks are very common and they can harm the privacy of your users. Like I mentioned above a user can intentionally inject malicious code into your website through your form input. And I am pretty sure that you don’t want that to happen.

There are two types of form validation:

Client-Side

The client-side validation is done in javascript. And it basically means that it happens before submitting the input data. This is helpful when you want the user to know right away that they have entered incorrect data. For example when a user is entering a value in the form, and as soon as they make a mistake they will get an error. This helps to avoid making unnecessary requests to the server.

Server-Side

This happens when a user has submitted the input data after the request to the server has been made. This is the most important type of validation. Because, if somehow the attackers get through the client-side validation they must not be able to get through the server-side validation. You have to make sure that any data that will be stored in your database is clean.

Writing the code

So, now that you know the importance of form validation, now I will tell you how to implement it. I will only be doing client-side validation.

There are many different ways of doing it. I am showing you the way I do it.

Simple JavaScript form validation

Let’s say that I have a simple login form on a website and below is the HTML and CSS for the form.

HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="wrapper">
    <div class="form-wrapper">
      <h2 class="title">Login to Your Account</h2>
      <form id="form" class="form">
        <div class="form-group">
          <label for="name">
            Email:
          </label>
          <input id="email" type="email" placeholder="[email protected]" required>
          <p id="emailError"></p>
        </div>
        <div class="form-group">
          <label for="password">
            Password:
          </label>
          <input id="password" type="password" placeholder="Enter Password" required>
          <p id="passwordError"></p>
        </div>
        <input type="submit" value="Login">
      </form>
    </div>
    <div class="success-msg-container">
      <h2 id="msg" class="msg">You have provided the correct details and your form will be processed</h2>
    </div>
  </div>
  <script src="script.js"></script>
</body>

</html>

Let’s also add the CSS to make the form appear good on the webpage.

CSS

@import url("https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@300;700&display=swap");

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  font-family: "Roboto Slab", serif;
}

.wrapper {
  width: 100%;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: linear-gradient(
    135deg,
    rgb(30, 250, 180),
    rgb(180, 30, 250)
  );
}

.form-wrapper {
  width: 100%;
  max-width: 500px;
  padding: 50px;

  background-color: white;
  box-shadow: 0 0 10px rgba(30, 250, 180, 0.4);
}

.title {
  margin-bottom: 50px;
  font-weight: bold;
  text-align: center;
  font-size: 2em;
  color: black;
}

.form-group {
  margin: 20px 0;
}

input {
  font-size: 30px;
  padding: 10px 20px;
  border-radius: 10px;
  border: none;
  outline: none;
  margin: 5px 0;
}

label {
  font-size: 15px;
  font-weight: bold;
}

input:not([type="submit"]) {
  width: 100%;
  border: 2px solid rgba(0, 0, 0, 0.7);
}

input[type="submit"] {
  background-color: rgb(8, 131, 92);
  color: white;
  font-size: 20px;
}
input[type="submit"]:hover {
  cursor: pointer;
  background-color: rgb(35, 235, 171);
}

input[type="submit"]:active {
  background-color: rgb(28, 80, 63);
}

.error #emailError,
.error #passwordError {
  color: red;
}
.error input {
  border: 2px solid red;
}

.msg {
  display: none;
}

After adding the HTML and CSS our webpage will look like this:

In the HTML you can see that I have a simple form with two inputs that ask for email and password. Now, what I want to do is that if a user enters a wrong email it would show a message “Please enter a valid email”. And similarly, if a user submits an empty form then I would show them an error message that would say “Please fill in the details”. So, now it is time to add javascript.

Javascript

const email = document.getElementById("email");
const password = document.getElementById("password"); 
const form = document.getElementById("form");
const msg = document.getElementById("msg");


// Function to validate the email
const validateEmail = (inputEmail)=> inputEmail.value.match(/^(([^<>()\[\]\\.,;:\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,}))$/);

// Function to validate password
const validatePassword = (inputPassword) => inputPassword.value.match(/^(([^<>()\[\]\\.,;:\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,}))$/);



// Function used to display errors
const generateError = (errorName, errorMsg) =>{
    const emailError = document.getElementById("emailError");
    const passwordError = document.getElementById("passwordError");
    if(errorName == "email"){
        emailError.innerText = errorMsg;    
    }else if(errorName == "password"){
        passwordError.innerText = errorMsg;
    }
}

const formValidate = (inputEmail, inputPassword) =>{
    if(!validateEmail(inputEmail)){
        emailError = "please enter a valid email address";
        generateError("email",emailError);
        return;
    }
    if(!validatePassword(inputPassword)){
        passwordError = "please enter correct password";
        generateError(generateError("password",passwordError));
        return;
    }
  
}

//triggers when user submits the form
form.addEventListener("submit",(e) => {
    e.preventDefault();
    formValidate(email, password);
});

// Focusout event listener. Triggers when the user clicks anywhere else besides the input
email.addEventListener("focusout", (e)=>{
    if(!validateEmail(email)){
        email.style.borderColor = "red";
        generateError("email", "Please enter a valid email");
        email.parentElement.classList.add("error");
    }
});

// Focusout event listener. Triggers when the user clicks anywhere else besides the input
password.addEventListener("focusout", (e)=>{
    if(!validatePassword(password)){
        password.style.borderColor = "red";
        generateError("password", "Please enter a valid password");
        password.parentElement.classList.add("error");
    }
});

Explanation

Now let me explain what I did in javascript. First, let’s talk about the email. It is pretty straightforward that, I want the user to enter only email and not anything else. One simple way of doing this is by making the input type=”email”.

<input id="email" type="email" placeholder="Enter email" required>

For the password, you have to use the input type=”password”.

<input id="password" type="password" placeholder="Enter password" required>

The next thing you can do is match whether the user has entered a valid email with the regex code which ensures that the user has entered a valid email address. I have also added the **“*required” ***attribute in the input tag this will not let the user process further without providing details.

The functions validateEmail and validatePassword matches the form value with the regex and return true or false based on the result. If there is an error then it will not process any further.

To display the error message I am simply selecting the specific element where I want to put the error message by using the “generateError” function.

emailError.innerText = errorMsg;

This is what it will look like:


Important note: There are a lot of people who do not properly validate forms and that results in a potential threat to sensitive data. So make it a habit of properly validating your forms not only on the client-side but server-side as well. Server-side validation is very important!

You can find the project on codepen. Feel free to use the code and do some changes if you think you can make it look better and more secure. Here is the live version of the code that I explained above:


See the Pen Form validation in javascript by Tamur


First Published here