Client-Side Form Validation with JavaScript
Javascript Tutorial

Client-Side Form Validation with JavaScript

3 min read

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!

About the Author

Matt Fay

Matt Fay

Matt is the founder of JavaScript Today, a platform dedicated to high-quality JavaScript education and commentary. With a deep curiosity for technology, he gravitates toward understanding how things work and has been diving into the world of information security. Outside of coding, Matt enjoys exploring languages; he can understand some Russian and Italian, and is currently learning Thai.

Learn AI Skills with Codecademy (729x90)

Discussion (Loading...)

Join the conversation

Join the Discussion

Sign in to share your thoughts and engage with the JavaScript Today community.

Loading comments...

Related Articles

Continue your learning journey with these related posts

Never Miss a JavaScript Update

Join our community of developers and receive insightful articles and coding tips every week.