MDN self-hosted library · e01.org

HTMLInputElement: reportValidity() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<p>
  <label for="age">Your (21 to 65) </label>
  <input type="number" name="age" required id="age" min="21" max="65" />
</p>
<p>
  <button type="button" id="report">reportValidity()</button>
</p>
<pre id="log"></pre>
js
const output = document.querySelector("#log");
const reportButton = document.querySelector("#report");
const ageInput = document.querySelector("#age");

ageInput.addEventListener("invalid", () => {
  output.textContent += "Invalid event fired.\n";
});

reportButton.addEventListener("click", () => {
  output.textContent = "";
  const reportVal = ageInput.reportValidity();
  output.textContent += `"reportValidity()" returned: ${reportVal}`;
  if (!reportVal) {
    output.textContent += `\nValidation message: "${ageInput.validationMessage}"`;
  }
});