Learn JavaScript Form Validation || JavaScript project for beginners✨
Tags: javascript, ccodenewbie, beginners, webdev
Published: 2021-09-23 11:54:06

Today we're gonna learn how to do form validation using JavaScript. And we're gonna add images and media queries to build the entire project to keep it as a portfolio. Here's the project demo that we're gonna build 👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vscg83vhkzb7m88l9w64.png)

Here's a small sample of how the form will work 👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cu7a6jb83jagx8gn7s98.gif)

## You can watch this tutorial on YouTube as well if you like:

{% youtube VufN46OyFng %}

## Source code

You can get the source code, including the images from here

- [CodePen](https://codepen.io/joyshaheb/pen/XWgdOyY)
- [GitHub](https://github.com/JoyShaheb/Project-image-repo/tree/main/Form-Validation)

## Setup

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtzp60xkbpi7seurz0iq.png)

follow these steps 👇

- Create a new folder named "Project" & Open VS code
- create index.html, style.css, main.js
- link the files inside the HTML
- Download [images from my GitHub repository](https://github.com/JoyShaheb/Project-image-repo/tree/main/Form-Validation)
- paste this font-awesome link inside the head tag. Then, we can access Font-awesome icons 👇

```HTML
<link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
      crossorigin="anonymous"
    />
```

## Table of Contents -

- writing the HTML
- Adding the CSS
- JavaScript
- Social Media Btn
- Adding the images
- Media query for mobile version

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9t8vie9mp0v5osi1br5d.png)

# HTML

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aiu9z7fdvly8bm85jaij.png)

Create a class named .container inside the body tag and host the form tag which will have an id of form 👇

```HTML
<div class="container">

	<form id="form"></form>

</div>
```

And inside the form tag, create 4 div. Like this 👇

```HTML
<form id="form">

    <div class="title">Get Started</div>

    <div></div>
    <div></div>
    <div></div>

</form>
```

Inside those 3 empty div tags, let's create 3 inputs [Username, Email & password] along with the icons and labels. Like this 👇

**Note :** we are creating a .error class name. We will inject the error message here using JavaScript.

## Username Input

```HTML
<!-- User Name input -->

<div>
	<label for="username">User Name</label>
    <i class="fas fa-user"></i>

    <input
        type="text"
        name="username"
        id="username"
        placeholder="Joy Shaheb"
     />

    <i class="fas fa-exclamation-circle failure-icon"></i>
    <i class="far fa-check-circle success-icon"></i>

    <div class="error"></div>

</div>
```

## Email Input

```HTML
<!-- Email input -->

<div>
	<label for="email">Email</label>
    <i class="far fa-envelope"></i>

    <input
        type="email"
        name="email"
        id="email"
        placeholder="abc@gmail.com"
     />

    <i class="fas fa-exclamation-circle failure-icon"></i>
    <i class="far fa-check-circle success-icon"></i>

    <div class="error"></div>

</div>
```

## Password Input

```HTML
<!--   Password input -->

<div>
	<label for="password">Password</label>
    <i class="fas fa-lock"></i>

    <input
        type="password"
        name="password"
        id="password"
        placeholder="Password here"
     />

    <i class="fas fa-exclamation-circle failure-icon"></i>
    <i class="far fa-check-circle success-icon"></i>

    <div class="error"></div>

</div>
```

## Button

Finally, add the button before the form closing tag

```HTML
<form>
    <!-- other codes are here -->

    <button id="btn" type="submit">Submit</button>

</form>
```

The result so far 👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3zdy5bxdxdi7xnbrosl.png)

Congrats for completing the HTML Part 🍾🎉🥂

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/acfquybwrpvac7b2anmv.png)

# Adding the CSS

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shqf98oz3w13l2mwsch2.png)

Let's add the CSS to style our form. First, let's remove the default styles of our browser including the font-family👇

```CSS
/**
* ! changing default styles of brower
**/

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

body {
  font-family: sans-serif;
}
```

Now, apply these styles for the form tag

```CSS
/**
* ! style rules for form section
**/

form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  max-width: 400px;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  padding: 50px;
}
```

make these changes for our title text 👇👇

```CSS
.title {
  font-size: 25px;
  font-weight: bold;
  margin-bottom: 20px;
}
```

Your result so far 👇👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/li2xh1mf3tzdvkshu4p1.png)

Now, add margin to bottom of our label text

```CSS
label {
  display: block;
  margin-bottom: 5px;
}
```

make these styles to change the look & feel of our input tags 👇👇

```CSS
form div input {
  width: 100%;
  height: 40px;
  border-radius: 8px;
  outline: none;
  border: 2px solid #c4c4c4;
  padding: 0 30px;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}
```

Add these to add some space & color changing effects

```CSS
form div {
  position: relative;
  margin-bottom: 15px;
}

input:focus {
  border: 2px solid #f2796e;
}
```

The result so far 👇👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p71pkg135w8bkd6edc7q.png)

## Styling the icons

now, we're gonna style the icons which we imported from font-awesome. Follow along ✨✨

```CSS
/**
* ! style rules for form icons
**/

form div i {
  position: absolute;
  padding: 10px;
}
```

The result of adding those 2 line 👇👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ueffrnf8opaluuwg0gt.png)

Now, add these styles to style the error class, success & failure icons 👇👇

```CSS
.failure-icon,
.error {
  color: red;
}

.success-icon {
  color: green;
}

.error {
  font-size: 14.5px;
  margin-top: 5px;
}
```

Result so far 👇👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vwd9tip3tfy082hjyqrx.png)

Look, the success & failure icons are overlapping each other. don't worry, we will manipulate those in JavaScript. for now, hide them 👇👇

```CSS
.success-icon,
.failure-icon {
  right: 0;
  opacity: 0;
}
```

Now, style our submit button, like this 👇

```CSS
/* Style rules for submit btn */

button {
  margin-top: 15px;
  width: 100%;
  height: 45px;
  background-color: #f2796e;
  border: 2px solid #f2796e;
  border-radius: 8px;
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.1s ease;
}
```

if you want some hover effect, then sure, add these styles 👇👇

```CSS
button:hover {
  opacity: 0.8;
}
```

# Take a Break !

So far so good ! take a break, you deserve it !

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ubi50ul7h4j8ikk0btt5.png)

# Adding the JavaScript

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dtdx1detnxbni64t8i64.png)

first, target all our classes and id from HTML, inside the JavaScript. To do this task efficiently, make these 2 functions 👇👇

```JS
let id = (id) => document.getElementById(id);

let classes = (classes) => document.getElementsByClassName(classes);
```

Then, store our classes & id inside these variables 👇

```JS
let username = id("username"),
  email = id("email"),
  password = id("password"),
  form = id("form"),

  errorMsg = classes("error"),
  successIcon = classes("success-icon"),
  failureIcon = classes("failure-icon");
```

**Note :** Try not to make spelling mistakes. Otherwise, our JavaScript will not work.

Now, we're gonna target our form & add the submit event listener 👇

```JS
form.addEventListener("submit", (e) => {
  e.preventDefault();
});
```

Now, we will create a function named engine which will do all sorts of form validation work for us. it will have 3 arguments. Follow along 👇

```JS
let engine = (id, serial, message) => {}
```

the arguments represents these -

- id = it will target our id
- serial = this will target our classes [error class, success & failure icons]
- message = this will print message inside our .error class

Now create an if, else statement like this 👇

```JS
let engine = (id, serial, message) => {

  if (id.value.trim() === "") {
  }

  else {
  }
}
```

**Note :** the id.value.trim() will remove all the extra white spaces from the value which the user inputs. You can get a practical idea by looking at this illustration 👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pf8l3rn804ysore8i4t8.png)

now, look at our objectives 👇

- we want the JavaScript to print a message inside the error class whenever the user submits the form blank. At the same time, we want the failure icons to highlight as well.

- But, if the user writes all the inputs and submits it, we want the success icon to get visible.

To accomplish this, write this logic 👇 To print the message

```JS
let engine = (id, serial, message) => {

  if (id.value.trim() === "") {
    errorMsg[serial].innerHTML = message;
  }

  else {
    errorMsg[serial].innerHTML = "";
  }
}
```

For the icons to work properly, add these 👇👇

```JS
let engine = (id, serial, message) => {

  if (id.value.trim() === "") {
    errorMsg[serial].innerHTML = message;
    id.style.border = "2px solid red";

    // icons
    failureIcon[serial].style.opacity = "1";
    successIcon[serial].style.opacity = "0";
  }

  else {
    errorMsg[serial].innerHTML = "";
    id.style.border = "2px solid green";

    // icons
    failureIcon[serial].style.opacity = "0";
    successIcon[serial].style.opacity = "1";
  }
}
```

Time to implement our newly created function. Write these inside the place where we added the submit event listener 👇

here, we are passing the id names, serials of our class names and passing the message which should be printed when we find an error when the user submits the form.

```JS
form.addEventListener("submit", (e) => {
  e.preventDefault();

  engine(username, 0, "Username cannot be blank");
  engine(email, 1, "Email cannot be blank");
  engine(password, 2, "Password cannot be blank");
});
```

The results so far 👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cu7a6jb83jagx8gn7s98.gif)

# Adding social media Buttons

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m1dav0ygxl9mopjoz0fy.png)

so far so good, let's add the social media sign up options. Follow along 👇 Inside the form tag, create a new div with the class name social.

```HTML
<form id="form">

    <div class="social">

      <div class="title">Get Started</div>

      <div class="question">
        Already Have an Account? <br />
        <span>Sign In</span>
      </div>

      <div class="btn"></div>

      <div class="or">Or</div>
    </div>

    <!-- other codes are here-->
</form>
```

inside the .btn class, we create 2 more div with class names .btn-1, .btn-2 with the images & text as well

```HTML
<div class="btn">
  <div class="btn-1">
     <img src="https://img.icons8.com/color/30/000000/google-logo.png" />
     Sign Up
  </div>

  <div class="btn-2">
    <img src="https://img.icons8.com/ios-filled/30/ffffff/facebook-new.png" />
     Sign Up
   </div>
</div>
```

The result so far 👇👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i29mmcgih9j2gwfnajnd.png)

Now, let's style the .btn-1 & .btn-2 first, let's change direction of the buttons to row from column direction 👇

```CSS
/**
* ! style rules for social section
**/

.btn {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 15px;
}
```

Result so far

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zfssxtyxxzsdcwpnnxxj.png)

now, add styles for the button. follow along 👇

```CSS
.btn-1,
.btn-2 {
  padding: 10px 5px;
  width: 100%;
  display: flex;
  gap: 15px;
  justify-content: center;
  align-items: center;
  border: 2px solid #c4c4c4;
  border-radius: 8px;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}
```

Change the icon color and text color of .btn-2 like this 👇

```CSS
.btn-2 {
  background-color: #4f70b5;
  color: white;
}
```

And then, add these small changes to make the component look better

```CSS
.or {
  text-align: center;
}

.question {
  font-size: 15px;
}

span {
  color: #f2796e;
  cursor: pointer;
}
```

The result so far

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2yix7r0zdb1fvwjipdji.png)

# Adding the Images

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/epyzh0hp5gb1mx9uqwte.png)

Now, let's add images to our project. First, let's write the HTML 👇

```HTML
<div class="container">

      <div class="content">
        <div class="logo">
          <img src="https://svgshare.com/i/_go.svg" alt="" />
        </div>

        <div class="image"></div>

        <div class="text">
          Start for free & get <br />
          attractive offers today !
        </div>
      </div>

   <form id="form">
   <!--other codes are here -->
   </form>

</div>
```

The result so far 👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t6gvlp4mot1m833uu536.png)

we need to change the orientation of our content from column to row. follow along 👇

```CSS
.container {
  display: flex;
  flex-direction: row;
}
```

Add these style rules for the content section

```CSS
/**
* ! style rules for content section
**/

.content {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  background-color: #f2796e;
  width: 55%;
  min-height: 100vh;
  padding: 10px 20px;
}

form {
   width: 45%;
   max-width: none;
}
```

The result so far 👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4aort4aq9rqutd204yv.png)

add the main illustration in CSS

```CSS
.image {
  background-image: url("https://svgshare.com/i/_gZ.svg");
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  /* border: 2px solid black; */
  height: 65%;
}
```

and make these styles for the .text class

```CSS
.text {
  text-align: center;
  color: white;
  font-size: 18px;
}

form {
   width: 45%;
   max-width: none;
}
```

The result so far 👇

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0zokq6cv3ezcs2mqsd3w.png)

# Adding media queries for mobile version

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m6zhny116iamqlradqjw.png)

from 900px, we will add these styles. Follow along 👇👇

```CSS
@media (max-width: 900px) {
  .container {
    flex-direction: column;
  }

  form,
  .content {
    width: 100%;
  }

  .btn {
    flex-direction: column;
  }
  .image {
    height: 70vh;
  }
}
```


From 425px, we will have these minor changes 👇

```CSS
@media (max-width: 425px) {
  form {
    padding: 20px;
  }
}
```

The final result 👇👇
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t2grfqf3joqdgzanjw23.gif)

# Conclusion

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pznmi45eize6jrabnlnt.png)

Congratulations for reading till the end. Now you can easily & efficiently use JavaScript to handle form validation. Not only that, You also have a project to show your local recruiter !

Here's Your Medal For reading till the end ❤️

## Suggestions & Criticisms Are Highly Appreciated ❤️

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/usxsz1lstuwry3jlly4d.png)

- [LinkedIn/ JoyShaheb](https://www.linkedin.com/in/joyshaheb/)
- [YouTube / JoyShaheb](https://www.youtube.com/c/joyshaheb)
- [Twitter / JoyShaheb](https://twitter.com/JoyShaheb)
- [Instagram / JoyShaheb](https://www.instagram.com/joyshaheb/)