Constraint Validation API

The browser can check form controls against HTML constraints such as required, type, min, and pattern.

What you will learn

Start with HTML

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

Use the most specific native input type and constraint that matches the data. The browser can prevent submission and provide built-in feedback.

Inspect validity

const form = document.querySelector('form');
const email = document.querySelector('#email');

form.addEventListener('submit', (event) => {
  if (!email.validity.valid) {
    event.preventDefault();
    email.focus();
  }
});

Properties such as validity.valueMissing and validity.typeMismatch explain why a control is invalid. Keep the message near the control and make it understandable without color alone.

Common mistakes