Client-Side Form Validation with JavaScript

Forms are everywhere. They allow us – the users – to input data and interact with applications.

Ensuring the accuracy and validity of user input is crucial. For example, in a previous article, we explored XSS (Cross-Site Scripting). Within that article, we see that properly handling user input is something that we should place high importance when creating web applications.

This article is going to dive into creating interactive form validations that enhance user experience and prevent error-prone submissions. We’ll be exploring server-side data validation in an upcoming article.

Understanding Form Validations

Form validations involve checking user input against predefined rules to ensure it meets the required criteria. We can perform these checks in real-time, providing instant feedback to users, letting them know what they’ve done wrong.

Common validations include checking for empty fields, validating email addresses, confirming password strength, and more.

Let’s look at an example.

Setting up a form

<form id="userForm">
    <label for="email">Email:</label>
    <input type="email" id="email" required>

    <label for="password">Password:</label>
    <input type="password" id="password" required>

    <button type="submit">Submit</button>
</form>
<div id="error-message"></div>

We just created a form with an email and password field. The form has an id of userForm and an empty div with an id of error-message, where our validation errors will be displayed.

Form Validation with JavaScript

Now, let’s add a script to create some simple form validations. We’ll use event listeners to validate the form as the user interacts with it.

const form = document.getElementById('userForm');
const email = document.getElementById('email');
const password = document.getElementById('password');
const errorMessage = document.getElementById('error-message');

form.addEventListener('submit', function(event) {
    let errors = [];
    
    if (email.value === '') {
        errors.push('Email is required.');
    } else if (!isValidEmail(email.value)) {
        errors.push('Invalid email address.');
    }

    if (password.value === '') {
        errors.push('Password is required.');
    } else if (password.value.length < 8) {
        errors.push('Password must be at least 8 characters long.');
    }

    if (errors.length > 0) {
        event.preventDefault();
        errorMessage.textContent = errors.join(' '); 
    }
});

function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

In this JavaScript code, we’re validating the email and password fields when the form is submitted. If there are validation errors, the form submission is prevented, and the errors will be pushed into the errors array.

The last step is check if errors.length is greater than zero. If it is, the error messages will be displayed.

Conclusion

Interactive form validations are a vital aspect of creating user-friendly web forms.

By leveraging JavaScript, developers can enhance the user experience by providing instant feedback and preventing invalid submissions. Remember, these validations can be extended to include additional fields and more complex rules, ensuring the accuracy and integrity of user data on your websites. If you’d like us to dig deeper into this topic, let us know down below.

Happy coding!

comments powered by Disqus

Related Posts

Gift Ideas for Developers and Tech Geeks

As the holiday season approaches, you may be wondering what gifts to get the developer in your life. Developers are unique creatures.

Read more

5 Useful JavaScript Snippets You Should Know About

In this article, we’re going to explore 5 different JavaScript snippets that you can use in your projects. Snippets are definitely useful to keep on hand, as you may never know when you’re going to need them, and there’s no point in rewriting code every time you need to get something done.

Read more

10 Common JavaScript Errors and How to Avoid Them

JavaScript, the backbone of modern web development, empowers developers to create dynamic and interactive websites. However, mastering this language comes with challenges.

Read more