DEV Community

Juan Garcia
Juan Garcia

Posted on

How can data validation for form inputs be handled both in HTML and JavaScript and Why is it beneficial to use both!

HTML handles data validation for forms through attributes that specify the type of input, the pattern or the minimal amount of characters we're expecting an user to enter on an specific field.

<input type="text" name="username" pattern="[A-Za-z]{5,9}" required>
Enter fullscreen mode Exit fullscreen mode

And we could simultaneously specify other input validation handlers using JavaScript.

document.querySelector('form');.addEventListener('click', (event) => {
    const username = document.querySelector("input[name='username']")
    if (username.value.length < 5) {
        event.preventDefault(); 
        alert("Username must be at least 5 characters long.");
    }
});
Enter fullscreen mode Exit fullscreen mode

The code above handles the submission of form input data by preventing the default behavior of the submission event until the username input is entered by a user with more than 5 characters.

It's beneficial to use both of these methods when validating form inputs because both offer different tools that when combined give us a more secure and dynamic way of validating form data.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay