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.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay