HTML5 form validation with button and JavaScript

Sometimes you'll need to validate and submit a form using JavaScript rather than using a standard submit button. Here is how you can trigger standard HTML5 form validation with JavaScript.

To perform standard form validation with a button and JavaScript, you can use the checkValidity() and reportValidity() methods.

Here's an example code snippet that demonstrates how to use these methods:

<form id="myForm">
  <input type="text" id="myInput" required>
  <button type="button" onclick="validateForm()">Submit</button>
</form>

<script>
  function validateForm() {
    var form = document.getElementById("myForm");
    var input = document.getElementById("myInput");

    if (input.checkValidity()) {
      // Valid input, do something
      alert("Form submitted successfully!");
    } else {
      // Invalid input, display error message
      input.reportValidity();
    }
  }
</script>

In this example, we have a form with a required input field and a button to submit the form. The validateForm() function is called when the button is clicked.

Inside the function, we get a reference to the form and input elements using their IDs. We then use the checkValidity() method on the input element to check if the user has entered a valid value.

If the value is valid, we can proceed with submitting the form or performing any other action. If the value is invalid, we use the reportValidity() method to display an error message to the user. This will prevent the form from being submitted until the user enters a valid value.

Note that the checkValidity() method checks for various constraints such as the required attribute, pattern matching, minimum and maximum values, etc. If you need to add custom validation, you can use the setCustomValidity() method on the input element to set a custom error message.

How to prevent (unintended) form submission

When using JavaScript for form validation, it's important to prevent the default form submission behavior, as this will bypass your validation code. You can do this by calling the preventDefault() method on the event object in your submit event listener.

document.querySelector('form').addEventListener('submit', function(event) {
  event.preventDefault(); // prevent form submission
  // perform validation code here
});

HTML5 form validation attributes

HTML5 introduces several form validation attributes that can be added to form elements to help ensure the data entered by the user is correct before submission. These attributes can be used in combination with JavaScript validation or on their own to provide a basic level of validation. Here are some of the most commonly used HTML5 form validation attributes:

required

This attribute specifies that an input field must be filled out before the form can be submitted.

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

min and max

These attributes specify the minimum and maximum allowed values for a numeric input.

<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="99">

pattern

This attribute specifies a regular expression pattern that the input value must match in order to be considered valid. For example, the following input field only accepts a valid email address:

<label for="email">Email:</label>
<input type="email" id="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" required>

maxlength and minlength

These attributes specify the maximum and minimum allowed length of a text input.

<label for="password">Password:</label>
<input type="password" id="password" name="password" minlength="8" maxlength="20" required>

autocomplete

This attribute specifies whether or not the browser should remember the value entered in the input field.

<label for="city">City:</label>
<input type="text" id="city" name="city" autocomplete="off">

Styling error messages

When using the reportValidity() method to display error messages, the browser will display default validation UI, which may not match your site's styling. Fortunately, you can customize the appearance of these messages using CSS or create your own custom error messages using JavaScript. Here are some ways to style error messages:

Using the :valid and :invalid pseudo-classes

You can use CSS to style input fields based on their validity state.

input:valid {
  border: 2px solid green;
}

input:invalid {
  border: 2px solid red;
}​

This will style valid input fields with a green border and invalid input fields with a red border.

Using the ::before and ::after pseudo-elements

You can use CSS to add custom error messages to input fields using the ::before and ::after pseudo-elements.

input:invalid + span::before {
  content: "✘ ";
  color: red;
}

input:valid + span::before {
  content: "✔ ";
  color: green;
}
​

This will add a red "✘" or green "✔" symbol before the error message text.

Using custom JavaScript error messages

You can use JavaScript to create your own custom error messages and display them in the DOM.

function validateForm() {
  var input = document.getElementById("myInput");
  var error = document.getElementById("error");

  if (input.checkValidity()) {
    error.innerHTML = "";
  } else {
    error.innerHTML = "Please enter a valid value.";
  }
}
​

In this example, we are using JavaScript to check the validity of the input field and display a custom error message in the #error element if the input is invalid. You can style the error message using CSS as you would any other DOM element.

By styling error messages, you can provide a more consistent and user-friendly experience for your users.

Validating multiple inputs

When you have multiple input fields in a form, you may want to validate them all at once to ensure that the user has entered valid values for all required fields. You can use the checkValidity() method on the entire form element to check all inputs at once. Here's an example:

<form id="myForm">
  <input type="text" id="name" name="name" required>
  <input type="email" id="email" name="email" required>
  <input type="tel" id="phone" name="phone">
  <button type="button" onclick="validateForm()">Submit</button>
</form>

<script>
  function validateForm() {
    var form = document.getElementById("myForm");
    if (form.checkValidity()) {
      // all inputs are valid, submit form
      form.submit();
    } else {
      // display error message
      form.reportValidity();
    }
  }
</script>

In this example, we have a form with three input fields and a button to submit the form. When the user clicks the submit button, the validateForm() function is called.

Inside the function, we get a reference to the form element using its ID. We then use the checkValidity() method on the form to check the validity of all inputs at once. If all inputs are valid, we can submit the form using the submit() method. If any input is invalid, we use the reportValidity() method to display an error message to the user.

Note that the checkValidity() method will return true if all required fields are filled out and have valid values, and will return false otherwise. If you need to check the validity of a specific input field, you can use the checkValidity() method on that input element instead of the entire form.

Updated