DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,911 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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

Бпасибо.

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›