Build a cat gallery application - Part 3

Build a cat gallery application - Part 3

Form validation with Javascript

If you visit the internet quite often, you may have come across forms on websites and web apps. These forms are used to collect user information which will then be sent to a server. Before submitting data to a server, it is necessary to ensure that the data is in the right format thus it is necessary to add validation to the forms.

For my cat gallery app, I wanted to implement a sign-up page where a user can create their account. But I don't think this page will serve its purpose correctly without validation.

Basically in this article, I will share with you how I added validations to my sign-up form using javascript, some concepts you should know before starting this task and some of the resources I used.

What to know? 🤔

A few concepts should not be ignored to carry out this task. Let's explore some of them.

  • Regular expressions, often shortened to "regex" or "regexp", are patterns that help programmers match, search, and replace text. ( Reference: regular expressions freeCodeCamp course )

    A pattern is the repeated or regular way something happens or is made.

For example, let's write a regular expression that matches all strings that start with the letter "a". The starts_with_a regular expression given above matches all strings that begin with the letter "a".

  let starts_with_a = /^a./;
  console.log(starts_with_a.test("antelope")); //true
  console.log(starts_with_a.test("cat")); //false

How will regular expressions be of help to us?

Let's take emails, for example, If we write a regex that matches all valid emails, we can use this to test for the validity of any email entered by a user. Such that an email such as "!something.ff" will be invalid and an email such as "" will be valid.

  • Document Object Model (DOM): This allows us to modify the HTML page with JavaScript. Here I needed to make sure I understood the DOM and how to manipulate it with JavaScript to get the result I wanted.

Below are some of the resources I used to learn these concepts. You might need to take some time out to study them.

Ps, you do not need to know everything about the regex and DOM before trying out this task but you surely need to know the basics. During the task, you may find yourself in circumstances where you need to make further research.

Let's code!

Before starting a task, I like to break it down into smaller tasks (mini-task) just like a to-do list. This gives me direction and gives me more control over the task.

In this section, I will present my to-do list but in there I'll be putting more details, images and code snippets. Let's go!🚀

  • Create an HTML file, a JavaScript file and a CSS file in the same folder.

In the HTML file

  • Write the HTML for a simple sign-up form
    • use input type text for the username
    • use input type email for the email
    • use input type password for the password

You can add as much styling as you want but it is not necessary at the moment

image.png

( For those who read my previous article, did you notice the styling of this page has changed? 😅 I couldn't stop myself from modifying it)

  • For each form field, write a corresponding error message in a p tag or small tag.
         <div class="contain-input">
            <label for="email"> Email </label>
            <input type="email" name="email" id="email" />
          </div>
          <small class="error" id="emailError">
            Email field should not be left empty
          </small>

With some styling, mine looks like this 👇

image.png

  • Link the JavaScript file to the HTML file using the script tag.

    I know why I'm saying this😶. I had forgotten to do it and kept wondering why my code was not working.

<script src="./validation.js"></script>

In the JavaScript file

  • Create variables to hold the regular expressions for the username, email and password.

    This is where I suffered most 😭, especially while writing the password regex and is also where I learnt a lot about regular expressions.

    Try to write your regular expressions on your own first, before asking for help from your peers or the internet. Your regular expression must neither be complete nor must it work on your first try. We aim to learn! and we learn by overcoming challenges.

Here are my regular expressions 👇. Read the comments to understand the expressions.

/* Username:
  1. must start with a letter
  2. should be at least 4 characters long */
let username_regex = /^[A-Za-z]+.{3,}$/;

/* email:
  1. the recipient's name and the domain name must start with a letter
  2. the recipient's name and the domain name can contain the characters ".", "-" and "_" 
  3. the top-level domain name should have 2 or 3 characters 
  4. there is a "." character between the domain name and the top-level domain name */

let email_regex = /^[A-Za-z]+[A-Za-z0-9.-_]*@[A-Za-z]+[A-Za-z0-9.-_]*.[a-z]{2,3}$/;

/* password:
  1. must contain at least one lowercase letter
  2. must contain at least one uppercase letter
  3. must contain at least one number
  4. must contain a special character
  5. should be at least 8 characters long */

let password_regex = /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[.'\@#-+=?/,+_()£"!$%^&*|])(?=.{8,})/;
  • Select the input elements and the error messages.
// select the form
const form = document.forms[0];

// select the error messages
const nameError = document.querySelector("#nameError");
const passError = document.querySelector("#passError");
const emailError = document.querySelector("#emailError");

// select the input elements in the form
const username = form.elements.username;
const email = form.elements.email;
const password = form.elements.password;
  • Write a function that checks for the validity of the inputs and then makes changes in the DOM.

    Let's have a summary of the function.

    • If a field is left empty, then the error message "The field should not be left empty" will be displayed.

    • If the input does not match the input's regex, then an error message "Input is invalid" will be displayed.

    • No errors are displayed when all inputs are valid and the user is redirected to another page.

function checkValid() {
    let passValid = true;
    let nameValid = true;
    let emailValid = true;

    if (!username_regex.test(username.value)) {
        if (username.value === '') {
            nameError.innerHTML = 'Username field should not be left empty'
        }
        else {
            nameError.innerHTML = 'Username is invalid'
        }
        nameValid = false;
        nameError.classList.add('show');
    }
    else {
        nameValid = true;
        nameError.classList.remove('show');
    }

    if (!email_regex.test(email.value)) {
        if (email.value === '') {
            emailError.innerHTML = 'Email field should not be left empty'
        }
        else {
            emailError.innerHTML = 'Email is invalid';
        }
        emailValid = false;
        emailError.classList.add('show');
    }
    else {
        emailValid = true;
        emailError.classList.remove('show');
    }


    if (!password_regex.test(password.value)) {
        if (password.value === '') {
            passError.innerHTML = 'Password field should not be left empty'
        }
        else {
            passError.innerHTML = 'Password is invalid';
        }
        passValid = false;
        passError.classList.add('show');
    }
    else {
        passValid = true;
        passError.classList.remove('show');
    }

    if (nameValid && emailValid && passValid) {
        location.href = "/homepage.html";
    }
}

Initially, the error message is not displayed which means in its CSS, we have display: none;. When an input is not valid, the function adds the 'show' class to its error message which gives it a block display ( display: block; )

  • Select the sign up button
const btn = document.querySelector("#sign-up-btn")
  • Add event listener to the button such that when the button is clicked, the checkValid() function is executed
btn.addEventListener("click", checkValid);

In the CSS file

  • Link the CSS file to the HTML file using the link tag.
<link rel="stylesheet" href="./style.css" />

The CSS should look similar to this one 👇

.error {
  display: none;
}

.error.show {
  display: block;
}

To conclude

There might be a million and one better ways out there to implement client-side validation in a form but I'm pretty much happy with what I've done already. As I learn more techniques in JavaScript, I'll probably find a better solution, and at that time, I'll come back here to update this article 🤗.

Thanks for your time and patience. Hope you learnt one or two things from here. If you have a review or comment, feel free to leave it in the comment section.