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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more