Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Forms and validity

Use `input` to react to edits and `submit` to handle a form submission after normal validation succeeds. `HTMLFormElement` also provides methods for explicitly checking form validity.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

field.addEventListener("input", handler); form.addEventListener("submit", handler); form.checkValidity(); form.reportValidity(); form.requestSubmit();

HTMLFormElement is the browser DOM interface for a form element. The form.elements property gives you access to the controls associated with the form. This is a Web API, not part of the ECMAScript language.

Listen for input to react to user edits, for example to update a hint as someone types. Assigning to field.value in JavaScript does not by itself fire input. The required attribute makes an empty text field invalid. form.checkValidity() returns a boolean result. form.reportValidity() also returns a boolean result and reports validation errors to the user unless the affected control’s invalid event is canceled. Canceling that event does not change the validation result: the method returns false without displaying an error for that control.

During a normal submission attempt, the browser checks constraints first. If a field is invalid, the browser blocks submission and no submit event fires. If validation succeeds, submit fires on the form, not on the button. Calling event.preventDefault() in that handler cancels the default submission.

Use form.requestSubmit() to start the same process from code. Calling form.submit() directly skips both validation and the submit event. Browser validation helps users correct their entries, but it does not replace server-side validation.

Examples

<!doctype html>
<meta charset="utf-8">
<title>Form validity</title>
<form id="profile">
  <label>Name <input name="displayName" required></label>
  <button type="submit">Save</button>
</form>
<pre id="log"></pre>
<script>
  const form = document.querySelector('#profile');
  const field = form.elements.namedItem('displayName');
  const log = document.querySelector('#log');
  const append = (line) => { log.textContent += line + '\n'; };

  field.addEventListener('input', () => {
    append(`input: ${form.checkValidity()}`);
  });
  form.addEventListener('submit', (event) => {
    event.preventDefault();
    append(`submit: ${field.value}`);
  });

  append(`initial: ${form.checkValidity()}`);
</script>

Result

initial: false
input: true
submit: A

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources