DEV Community

Cover image for Learn JavaScript Form Validation || JavaScript project for beginners✨
Joy Shaheb
Joy Shaheb

Posted on • Updated on • Originally published at freecodecamp.org

Learn JavaScript Form Validation || JavaScript project for beginners✨

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

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

Alt Text

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

Source code

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

Setup

Alt Text

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
  • paste this font-awesome link inside the head tag. Then, we can access Font-awesome icons 👇
<link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
      crossorigin="anonymous"
    />
Enter fullscreen mode Exit fullscreen mode

Table of Contents -

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

Alt Text

HTML

Alt Text

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

<div class="container">

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

</div>
Enter fullscreen mode Exit fullscreen mode

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

<form id="form">

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

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

</form>
Enter fullscreen mode Exit fullscreen mode

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

<!-- 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>
Enter fullscreen mode Exit fullscreen mode

Email Input

<!-- 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>
Enter fullscreen mode Exit fullscreen mode

Password Input

<!--   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>
Enter fullscreen mode Exit fullscreen mode

Button

Finally, add the button before the form closing tag

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

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

</form>
Enter fullscreen mode Exit fullscreen mode

The result so far 👇

Alt Text

Congrats for completing the HTML Part 🍾🎉🥂

Alt Text

Adding the CSS

Alt Text

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

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

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

body {
  font-family: sans-serif;
}
Enter fullscreen mode Exit fullscreen mode

Now, apply these styles for the form tag

/**
* ! 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;
}
Enter fullscreen mode Exit fullscreen mode

make these changes for our title text 👇👇

.title {
  font-size: 25px;
  font-weight: bold;
  margin-bottom: 20px;
}
Enter fullscreen mode Exit fullscreen mode

Your result so far 👇👇

Alt Text

Now, add margin to bottom of our label text

label {
  display: block;
  margin-bottom: 5px;
}
Enter fullscreen mode Exit fullscreen mode

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

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);
}
Enter fullscreen mode Exit fullscreen mode

Add these to add some space & color changing effects

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

input:focus {
  border: 2px solid #f2796e;
}
Enter fullscreen mode Exit fullscreen mode

The result so far 👇👇

Alt Text

Styling the icons

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

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

form div i {
  position: absolute;
  padding: 10px;
}
Enter fullscreen mode Exit fullscreen mode

The result of adding those 2 line 👇👇

Alt Text

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

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

.success-icon {
  color: green;
}

.error {
  font-size: 14.5px;
  margin-top: 5px;
}
Enter fullscreen mode Exit fullscreen mode

Result so far 👇👇

Alt Text

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

.success-icon,
.failure-icon {
  right: 0;
  opacity: 0;
}
Enter fullscreen mode Exit fullscreen mode

Now, style our submit button, like this 👇

/* 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;
}
Enter fullscreen mode Exit fullscreen mode

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

button:hover {
  opacity: 0.8;
}
Enter fullscreen mode Exit fullscreen mode

Take a Break !

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

Alt Text

Adding the JavaScript

Alt Text

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

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

let classes = (classes) => document.getElementsByClassName(classes);
Enter fullscreen mode Exit fullscreen mode

Then, store our classes & id inside these variables 👇

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

  errorMsg = classes("error"),
  successIcon = classes("success-icon"),
  failureIcon = classes("failure-icon");
Enter fullscreen mode Exit fullscreen mode

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 👇

form.addEventListener("submit", (e) => {
  e.preventDefault();
});
Enter fullscreen mode Exit fullscreen mode

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 👇

let engine = (id, serial, message) => {}
Enter fullscreen mode Exit fullscreen mode

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 👇

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

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

  else {
  }
}
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

  else {
    errorMsg[serial].innerHTML = "";
  }
}
Enter fullscreen mode Exit fullscreen mode

For the icons to work properly, add these 👇👇

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";
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

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");
});
Enter fullscreen mode Exit fullscreen mode

The results so far 👇

Alt Text

Adding social media Buttons

Alt Text

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.

<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>
Enter fullscreen mode Exit fullscreen mode

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

<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>
Enter fullscreen mode Exit fullscreen mode

The result so far 👇👇

Alt Text

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

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

.btn {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 15px;
}
Enter fullscreen mode Exit fullscreen mode

Result so far

Alt Text

now, add styles for the button. follow along 👇

.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;
}
Enter fullscreen mode Exit fullscreen mode

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

.btn-2 {
  background-color: #4f70b5;
  color: white;
}
Enter fullscreen mode Exit fullscreen mode

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

.or {
  text-align: center;
}

.question {
  font-size: 15px;
}

span {
  color: #f2796e;
  cursor: pointer;
}
Enter fullscreen mode Exit fullscreen mode

The result so far

Alt Text

Adding the Images

Alt Text

Now, let's add images to our project. First, let's write the 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>
Enter fullscreen mode Exit fullscreen mode

The result so far 👇

Alt Text

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

.container {
  display: flex;
  flex-direction: row;
}
Enter fullscreen mode Exit fullscreen mode

Add these style rules for the content section

/**
* ! 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;
}
Enter fullscreen mode Exit fullscreen mode

The result so far 👇

Alt Text

add the main illustration in 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%;
}
Enter fullscreen mode Exit fullscreen mode

and make these styles for the .text class

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

form {
   width: 45%;
   max-width: none;
}
Enter fullscreen mode Exit fullscreen mode

The result so far 👇

Alt Text

Adding media queries for mobile version

Alt Text

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

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

  form,
  .content {
    width: 100%;
  }

  .btn {
    flex-direction: column;
  }
  .image {
    height: 70vh;
  }
}
Enter fullscreen mode Exit fullscreen mode

From 425px, we will have these minor changes 👇

@media (max-width: 425px) {
  form {
    padding: 20px;
  }
}
Enter fullscreen mode Exit fullscreen mode

The final result 👇👇
Alt Text

Conclusion

Alt Text

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

Top comments (2)

Collapse
 
firefox700101 profile image
Raymond

This is an amazing course. Thank you Joy. Very impressive.

Collapse
 
evgenijvasiliev profile image
Evgenij-Vasiliev

Спасибо.