How to Validate Form Inputs with JavaScript on Submit?

Estimated read time 3 min read

You can validate form inputs with JavaScript by attaching an event listener to the form’s submit event, and then checking the validity of each input field using various validation techniques.

Here’s an example of how to validate a form that contains an input field for a name, email, and password:

<!DOCTYPE html>
<html>
<head>
  <title>Form Validation Example</title>
</head>
<body>

  <form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

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

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

    <button type="submit">Submit</button>
  </form>

  <script>
    const myForm = document.getElementById("myForm");

    myForm.addEventListener("submit", (event) => {
      // prevent the form from submitting if any input is invalid
      if (!myForm.checkValidity()) {
        event.preventDefault();
        return;
      }

      // perform any other validation here
      // ...

      // if all inputs are valid, submit the form
      alert("Form submitted successfully!");
    });
  </script>

</body>
</html>

In this code, an HTML form element is created with three input elements of different types: “text”, “email”, and “password”. Each input element is required, which means that the user must enter a value before the form can be submitted.

The JavaScript code then uses the document.getElementById() method to get a reference to the form, and the addEventListener() method to attach a submit event listener to it.

The event listener is an arrow function that takes an event parameter, representing the submit event object. The checkValidity() method is called on the form object to check whether all input fields are valid. If any input field is invalid, the preventDefault() method is called on the event object to prevent the form from submitting, and the function returns. Otherwise, any other validation logic can be performed, and if all inputs are valid, an alert is displayed indicating that the form was submitted successfully.

You can customize the validation logic to suit your specific requirements, such as checking for a minimum length or format of the input, or comparing two fields to ensure that they match.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply