← Back to JavaScript, page 10

javascript-0183 · Medium mid

How do you read a form with FormData and validate it, and what are the common traps with checkboxes, multiple values, and disabled fields?

new FormData(form) collects the successful controls, so unchecked checkboxes, disabled fields, and fields without a name are missing. Use getAll for repeated names because Object.fromEntries keeps only the last value, convert types yourself, and trim text. For validation, combine the built-in constraint API (checkValidity, validity, setCustomValidity) with custom checks and show messages next to the fields.

Full answer

new FormData(form) builds the same data the browser would submit. It includes controls that have a name and are not disabled. Unchecked checkboxes and radios are left out, and a select multiple gives one entry per selected option. File inputs give File objects. Submit buttons are included only if you pass the submitter as the second argument.

Reading the data:

  • formData.get('name') returns the first value as a string or file, or null if missing. getAll('tags') returns an array.
  • Object.fromEntries(formData) is a quick way to get an object, but repeated names collapse to the last value. Build the object in a loop and use getAll for fields that can repeat.
  • Values are strings, so convert numbers (Number(value)), dates, and booleans yourself. An unchecked checkbox is missing, so use formData.has('agree') to get a boolean.
  • Trim text before validating, and do not trust client values on the server.

Validation layers:

  1. Built-in constraints in HTML: required, type="email", pattern, min, max, minlength. form.checkValidity() and input.validity (valueMissing, typeMismatch, patternMismatch, rangeUnderflow) read them in JavaScript. input.setCustomValidity('message') adds a custom error, and an empty string clears it.
  2. Custom rules for cross-field logic, such as password confirmation.
  3. Show errors near the field, link them with aria-describedby, set aria-invalid, move focus to the first invalid field, and use novalidate on the form if you want your own messages for all rules.
  4. Listen to the submit event on the form (not the click of the button), call preventDefault() when you handle it yourself, and use event.submitter to know which button was used.

Do not forget to rerun the same validation on the server, since the client can be bypassed.

javascript
document.body.innerHTML = `
  <form id="signup" novalidate>
    <input name="email" type="email" required value="asha@example.com">
    <input name="age" type="number" min="18" max="99" value="17">
    <input name="password" type="password" required value="secret123">
    <input name="confirm" type="password" value="secret124">
    <input type="checkbox" name="interests" value="js" checked>
    <input type="checkbox" name="interests" value="css" checked>
    <input type="checkbox" name="interests" value="sql">
    <input type="checkbox" name="agree">
    <input name="nickname" value="hidden one" disabled>
    <input value="no name given">
    <select name="plan"><option value="free">Free</option><option value="pro" selected>Pro</option></select>
    <button name="action" value="save">Save</button>
  </form>`;
const form = document.getElementById('signup');

const data = new FormData(form);
console.log('entries:', JSON.stringify([...data.entries()]));
console.log('fromEntries loses repeats:', JSON.stringify(Object.fromEntries(data).interests));
console.log('getAll:', data.getAll('interests'), '| has agree:', data.has('agree'), '| get missing:', data.get('agree'));

function readForm(formElement) {
  const formData = new FormData(formElement);
  return {
    email: String(formData.get('email') ?? '').trim().toLowerCase(),
    age: Number(formData.get('age')),
    interests: formData.getAll('interests'),
    agree: formData.has('agree'),
    plan: formData.get('plan'),
    password: formData.get('password'),
    confirm: formData.get('confirm'),
  };
}

function validate(formElement) {
  const values = readForm(formElement);
  const errors = {};
  for (const field of formElement.elements) {
    if (!field.name || field.disabled) continue;
    field.setCustomValidity('');
  }
  if (values.password !== values.confirm) formElement.elements.confirm.setCustomValidity('Passwords do not match');
  for (const field of formElement.elements) {
    if (!field.name || field.disabled || field.willValidate === false) continue;
    if (!field.checkValidity()) {
      const flags = Object.keys(Object.getPrototypeOf(field.validity)).filter((key) => key !== 'valid' && field.validity[key]);
      errors[field.name] = flags.join(',') + (field.validationMessage && flags.includes('customError') ? ': ' + field.validationMessage : '');
    }
  }
  if (!values.agree) errors.agree = 'terms must be accepted (custom rule)';
  return { values, errors };
}

const result = validate(form);
console.log('values:', JSON.stringify(result.values));
console.log('errors:', JSON.stringify(result.errors));

form.elements.age.value = '30';
form.elements.confirm.value = 'secret123';
form.elements.agree.checked = true;
form.elements.email.value = 'not-an-email';
console.log('after fixes:', JSON.stringify(validate(form).errors));

form.elements.email.value = 'ben@example.com';
console.log('all good:', JSON.stringify(validate(form).errors), '| form.checkValidity():', form.checkValidity());

const submitterData = new FormData(form, form.querySelector('button'));
console.log('with the submitter:', submitterData.get('action'), '| without:', new FormData(form).get('action'));

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: entries: [["email","asha@example.com"],["age","17"],["password","secret123"],["confirm","secret124"],["interests","js"],["interests","css"],["plan","pro"]] fromEntries loses repeats: "css" getAll: [ 'js', 'css' ] | has agree: false | get missing: null values: {"email":"asha@example.com","age":17,"interests":["js","css"],"agree":false,"plan":"pro","password":"secret123","confirm":"secret124"} errors: {"age":"rangeUnderflow","confirm":"customError: Passwords do not match","agree":"terms must be accepted (custom rule)"} after fixes: {"email":"typeMismatch"} all good: {} | form.checkValidity(): true with the submitter: save | without: null

Key points

  • FormData has only named, enabled, successful controls; unchecked checkboxes are absent.
  • Use getAll for repeated names; Object.fromEntries keeps the last one.
  • All values are strings; convert and trim them yourself.
  • Use the constraint validation API plus custom rules; connect errors with aria attributes.
  • Handle the submit event, and validate again on the server.

Common mistakes

  • Expecting unchecked checkboxes or disabled fields in FormData.
  • Using Object.fromEntries on forms with repeated names.
  • Forgetting that all values are strings.
  • Trusting client validation without checking on the server.

Follow-ups

  • How do you validate a field on blur and again on input?
  • How do you make error messages accessible to screen readers?
  • How would you send the same data as JSON and as multipart?

Tips

  • List what FormData leaves out; interviewers ask about it.
  • Show getAll for multi-value fields.
  • Mention server-side validation and accessible error messages.