Forms and validation

A form is the part of a page that collects values, and the DOM exposes every field as an element with a value and a validity. The browser checks a few rules without any JavaScript: a required field, the shape of an email address, a number inside a range. A program adds the rules the browser cannot know and reports the problems at the right place.

The four programs of this lesson read the fields of one signup form, ask the browser what is wrong with them, report every problem in a paragraph of the page and then take the whole form as one object. They run in jsdom, set up as the first lesson of this part showed, and jsdom implements the same constraint validation as a browser, with messages of its own wording.

Reading the fields

form.elements holds every control of the form in document order, and a name that is unique on the form can be read as a property of that collection. An input has a string value whatever its type, plus valueAsNumber for a numeric one, a checked flag when it is a checkbox, and a select keeps its chosen option in value as well. Reading a field that the form does not have gives undefined, which is the error at the end of the program.

The program prints the value of each kind of field, writes two of them and reads them back, and then reads a field whose name is a typo.

The file values.js:

const { JSDOM } = require('jsdom'); const html = [ '<!doctype html>', '<body>', '<form id="signup">', '<input name="email" type="email" required>', '<input name="age" type="number" min="18" max="120" value="36">', '<input name="terms" type="checkbox" required>', '<select name="colour"><option value="red">red</option><option value="blue" selected>blue</option></select>', '<button type="submit">save</button>', '</form>', '</body>', ].join(''); const dom = new JSDOM(html, { url: 'http://localhost/signup' }); const { document } = dom.window; const form = document.querySelector('#signup'); const { elements } = form; console.log('the number of fields:', elements.length); console.log('the email:', JSON.stringify(elements.email.value)); console.log('the age as text:', elements.age.value); console.log('the age as a number:', elements.age.valueAsNumber); console.log('the checkbox:', elements.terms.checked); console.log('the select:', elements.colour.value); console.log('a number from a text field:', Number.isNaN(elements.email.valueAsNumber)); elements.email.value = 'ada@example.com'; elements.terms.checked = true; console.log('after the writes:', elements.email.value, elements.terms.checked); console.log('the fields in order:', Array.from(elements).map((field) => field.name || field.tagName.toLowerCase()).join(', ')); try { console.log(elements.missing.value); } catch (error) { console.log('the error:', error.name, '-', error.message); }

node values.js

the number of fields: 5
the email: ""
the age as text: 36
the age as a number: 36
the checkbox: false
the select: blue
a number from a text field: true
after the writes: ada@example.com true
the fields in order: email, age, terms, colour, button
the error: TypeError - Cannot read properties of undefined (reading 'value')

The email arrived as an empty string and not as null, the age is text in one line and a number in the next, and the select answered with the value of the option that the markup marked as selected. The button is in the collection as well, which is why a loop over the fields has to skip the controls that carry no value.

What the browser checks

checkValidity() answers a boolean, on a field and on the form as a whole, and validity says why: valueMissing, typeMismatch, rangeUnderflow, rangeOverflow and a few more. The flags are what a program tests, because validationMessage is text written by the browser and translated for the reader: the same failure has a different sentence in another browser and another language.

The program breaks one rule at a time on the same form and prints the flag that belongs to each break.

The file validity.js:

const { JSDOM } = require('jsdom'); const html = [ '<!doctype html>', '<body>', '<form id="signup">', '<input name="email" type="email" required>', '<input name="age" type="number" min="18" max="120">', '<input name="terms" type="checkbox" required>', '<button type="submit">save</button>', '</form>', '</body>', ].join(''); const dom = new JSDOM(html, { url: 'http://localhost/signup' }); const { document } = dom.window; const form = document.querySelector('#signup'); const { email, age, terms } = form.elements; console.log('an empty email is valid:', email.checkValidity()); console.log('the message:', JSON.stringify(email.validationMessage)); console.log('valueMissing:', email.validity.valueMissing); email.value = 'not an address'; console.log('a bad address is valid:', email.checkValidity()); console.log('typeMismatch:', email.validity.typeMismatch); email.value = 'ada@example.com'; console.log('a good address is valid:', email.checkValidity(), 'the message:', JSON.stringify(email.validationMessage)); age.value = '12'; console.log('too young is valid:', age.checkValidity()); console.log('rangeUnderflow:', age.validity.rangeUnderflow); age.value = '200'; console.log('too old is valid:', age.checkValidity(), 'rangeOverflow:', age.validity.rangeOverflow); age.value = '36'; terms.checked = true; console.log('the whole form is valid:', form.checkValidity()); terms.checked = false; console.log('after clearing the checkbox:', form.checkValidity(), 'reportValidity:', form.reportValidity());

node validity.js

an empty email is valid: false
the message: "Constraints not satisfied"
valueMissing: true
a bad address is valid: false
typeMismatch: true
a good address is valid: true the message: ""
too young is valid: false
rangeUnderflow: true
too old is valid: false rangeOverflow: true
the whole form is valid: true
after clearing the checkbox: false reportValidity: false

The message of an empty email is one sentence and the message of a bad address is the same sentence, which is exactly why a program reads the flag and not the text. reportValidity answers the same boolean as checkValidity; in a browser it also shows the message to the reader, and in jsdom it only answers, because there is no one to show it to.

A form that reports its own errors

A submit handler runs before the form is sent, and preventDefault cancels the sending so the page can stay where it is. That is the moment to collect the problems: a loop over the fields, a check of each one, and one paragraph that lists every failure instead of the first one. A reader who has to fix three fields wants to see three messages and not to submit the form three times.

The program submits the form empty, then with an address only, then with everything filled in, and prints the paragraph after each attempt.

The file submit.js:

const { JSDOM } = require('jsdom'); const html = [ '<!doctype html>', '<body>', '<form id="signup">', '<input name="email" type="email" required>', '<input name="age" type="number" min="18" max="120">', '<input name="terms" type="checkbox" required>', '<button type="submit">save</button>', '</form>', '<p id="report"></p>', '</body>', ].join(''); const dom = new JSDOM(html, { url: 'http://localhost/signup' }); const { window } = dom; const { document } = window; const form = document.querySelector('#signup'); const report = document.querySelector('#report'); form.addEventListener('submit', (event) => { event.preventDefault(); const problems = []; for (const field of form.elements) { if (field.checkValidity()) { continue; } problems.push(`${field.name}: ${field.validationMessage}`); } report.textContent = problems.length === 0 ? 'saved' : problems.join('; '); }); function submit() { form.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true })); console.log('the report:', report.textContent); } submit(); form.elements.email.value = 'ada@example.com'; submit(); form.elements.age.value = '36'; form.elements.terms.checked = true; submit();

node submit.js

the report: email: Constraints not satisfied; terms: Constraints not satisfied
the report: terms: Constraints not satisfied
the report: saved

The first attempt reported two fields and the second reported one, and the messages came from the browser rather than from the program. The last attempt would send the form in a real page, because the handler allows the default action when there is nothing to report, which is the branch this program only reads as a word in the paragraph.

The form as one object

new FormData(form) collects the successful controls of a form and keeps their names and values, and Object.fromEntries turns that into a plain object in one line. An unchecked checkbox is not a successful control, so it is absent rather than false, and a number arrives as text because a form sends text. The object is what a program sends as JSON, and it is the same data that a browser would put on the wire.

The program reads the form as data, then changes and adds an entry to show how the object behaves.

The file formdata.js:

const { JSDOM } = require('jsdom'); const html = [ '<!doctype html>', '<body>', '<form id="signup">', '<input name="email" type="email" value="ada@example.com">', '<input name="age" type="number" value="36">', '<input name="terms" type="checkbox">', '<select name="colour"><option value="red">red</option><option value="blue" selected>blue</option></select>', '<button type="submit">save</button>', '</form>', '</body>', ].join(''); const dom = new JSDOM(html, { url: 'http://localhost/signup' }); const { window } = dom; const { document } = window; const form = document.querySelector('#signup'); const data = new window.FormData(form); console.log('the entries:', Array.from(data.keys()).join(', ')); console.log('the email:', data.get('email')); console.log('the age arrives as text:', JSON.stringify(data.get('age'))); console.log('the unchecked box is absent:', data.get('terms')); console.log('as a plain object:', JSON.stringify(Object.fromEntries(data))); data.set('email', 'grace@example.com'); data.append('tag', 'note'); console.log('after set and append:', JSON.stringify(Object.fromEntries(data)));

node formdata.js

the entries: email, age, colour
the email: ada@example.com
the age arrives as text: "36"
the unchecked box is absent: null
as a plain object: {"email":"ada@example.com","age":"36","colour":"blue"}
after set and append: {"email":"grace@example.com","age":"36","colour":"blue","tag":"note"}

The checkbox is missing from the three entries, and the number arrived in quotes. A server that reads this data has to know that the absence of a checkbox means false and that a number is text until the program converts it, which is the difference between what a form sends and what an JSON body carries.

Exercises

  1. Add a field with type="url" and a value that is not an address. Which flag of validity is true?
  2. Set age.value to abc on the number input. What does valueAsNumber answer, and which flag reports the problem?
  3. Check the form with the email filled in and the checkbox still empty. Which status does form.checkValidity() answer, and which field is to blame?
  4. Report the problems in a list instead of one line, one li per field. Which lesson of this part built a list from an array of records?
  5. Count the fields that a FormData collects and compare it with form.elements.length. Which controls are missing, and why?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How does a program read the text of an input?

    Answer

    From the value property of the element

    A control keeps what the reader typed in value, while its text is the markup around it.

  2. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<form><input name=age type=number value=36></form>", { url: "http://localhost/" }); const age = dom.window.document.querySelector("input"); console.log(age.valueAsNumber, typeof age.valueAsNumber);

    Answer

    36 number

    A number input turns its text into a number for this property, which is what arithmetic needs.

  3. What does checkValidity answer for an empty required field?

    Answer

    false

    An empty required field breaks a rule, so the boolean is false and valueMissing is true.

  4. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<form><input name=email type=email required></form>", { url: "http://localhost/" }); const email = dom.window.document.querySelector("input"); console.log(email.checkValidity(), email.validity.valueMissing);

    Answer

    false true

    The field is empty and required, so the form check fails and the missing value is the reason.

  5. Why does a program read validity flags rather than validationMessage?

    Answer

    The message is the text of the browser and differs between browsers and languages

    The flags are part of the standard and the sentence is not, so logic on the text breaks somewhere else.

  6. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<form><input name=email type=email value=ada@example.com><input name=terms type=checkbox required></form>", { url: "http://localhost/" }); const form = dom.window.document.querySelector("form"); console.log(form.checkValidity());

    Answer

    false

    One control breaks a rule, and the form is invalid as soon as one of its fields is invalid.

  7. What does FormData do with a checkbox that is not checked?

    Answer

    It leaves the name out of the data

    Only successful controls are collected, and an unchecked box is not one of them.

  8. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<form><input name=age type=number value=36></form>", { url: "http://localhost/" }); const form = dom.window.document.querySelector("form"); const data = new dom.window.FormData(form); console.log(data.get("age"), typeof data.get("age"));

    Answer

    36 string

    A form sends text, so every value of FormData is a string whatever the type of the input.

  9. What does preventDefault in a submit handler stop?

    Answer

    The browser sending the form to the address in the action

    The event has already reached the handler; what is cancelled is the default action that follows it.

  10. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<form><input name=age type=number min=18 value=12></form>", { url: "http://localhost/" }); const age = dom.window.document.querySelector("input"); console.log(age.checkValidity(), age.validity.rangeUnderflow);

    Answer

    false true

    The value is below the minimum of the input, so the field is invalid and the flag names the reason.

The programs on this page were run with Node.js 24.22.1 against jsdom 30.1.3 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev