Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Form state reducer with dirty fields in JavaScript

92 A form reducer that tracks dirty fields and hides errors until asked

fair

Write a pure reducer for one form: change, blur, submit and reset. Validate on every change, but only show an error for a field the user has touched, and reveal all of them on submit. Report which fields differ from the values the form opened with, and make sure typing a value back to its original clears that.

Stuck? Three hints, smallest first
  1. 1. Keep the values it opened with alongside the current ones. Dirty is a comparison, not a flag you set.
  2. 2. Validate the whole values object on every change; decide separately what to display.
  3. 3. A reducer returns a new object for a change it understood and the same object for one it did not.

The answer

const validate = (values) => {
  const errors = {};
  if (values.fullName.trim() === '') errors.fullName = 'Name is required';
  if (!/^0\d{10}$/.test(values.phone)) errors.phone = 'Enter an 11-digit number, e.g. 08031234567';
  if (!(values.amountKobo > 0)) errors.amountKobo = 'Enter an amount';
  return errors;
};

const createForm = (values) => ({
  values,
  opened: values,
  touched: {},
  errors: validate(values),
  submitted: false,
});

function reduce(state, action) {
  switch (action.type) {
    case 'change': {
      const values = { ...state.values, [action.field]: action.value };
      return { ...state, values, errors: validate(values) };
    }
    case 'blur':
      return { ...state, touched: { ...state.touched, [action.field]: true } };
    case 'submit': {
      const touched = Object.fromEntries(Object.keys(state.values).map((field) => [field, true]));
      return { ...state, touched, submitted: true };
    }
    case 'reset':
      return createForm(state.opened);
    default:
      return state;                       // unknown action: the very same object back
  }
}

const dirtyFields = (state) => Object.keys(state.values).filter((f) => state.values[f] !== state.opened[f]);
const shownErrors = (state) => Object.fromEntries(Object.entries(state.errors).filter(([f]) => state.touched[f]));
const isValid = (state) => Object.keys(state.errors).length === 0;
const drive = (state, ...actions) => actions.reduce(reduce, state);

const fresh = createForm({ fullName: '', phone: '', amountKobo: 0 });

const typed = drive(fresh, { type: 'change', field: 'fullName', value: 'Ada' });
const openedIntact = fresh.values.fullName;

const typedBack = drive(typed, { type: 'change', field: 'fullName', value: '' });

const badPhone = drive(typed, { type: 'change', field: 'phone', value: '0803123' });
const blurred = drive(badPhone, { type: 'blur', field: 'phone' });

const submitted = drive(badPhone, { type: 'submit' });

const good = drive(
  fresh,
  { type: 'change', field: 'fullName', value: 'Adaeze Okonkwo' },
  { type: 'change', field: 'phone', value: '08031234567' },
  { type: 'change', field: 'amountKobo', value: 250000 },
  { type: 'submit' }
);

const afterReset = drive(good, { type: 'reset' });
const ignored = reduce(good, { type: 'nothing-we-know' });

console.log('fresh    : dirty', dirtyFields(fresh), 'shown', shownErrors(fresh), 'valid', isValid(fresh));
console.log('typed    : dirty', dirtyFields(typed));
console.log('blurred  : shown', shownErrors(blurred));
console.log('submitted: shown', Object.keys(shownErrors(submitted)));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a form that just opened is clean and shows nothing, though it is not valid', [dirtyFields(fresh), shownErrors(fresh), isValid(fresh)], [[], {}, false]);
test('changing a field makes it dirty and leaves the previous state alone', [dirtyFields(typed), openedIntact], [['fullName'], '']);
test('typing the original value back clears dirty rather than latching it', dirtyFields(typedBack), []);
test('an invalid field has an error immediately but shows nothing until it is touched', [Object.keys(badPhone.errors), shownErrors(badPhone)], [['phone', 'amountKobo'], {}]);
test('blur is what reveals that one field\'s error', shownErrors(blurred), { phone: 'Enter an 11-digit number, e.g. 08031234567' });
test('submit touches everything, so every outstanding error appears at once', Object.keys(shownErrors(submitted)), ['phone', 'amountKobo']);
test('a properly filled form submits with nothing to show', [isValid(good), shownErrors(good), good.submitted], [true, {}, true]);
test('reset goes back to the values it opened with and forgets the touching', [afterReset.values, afterReset.touched, dirtyFields(afterReset)], [{ fullName: '', phone: '', amountKobo: 0 }, {}, []]);
test('an action the reducer does not know returns the identical object, so nothing re-renders', ignored === good, true);

Dirty as a derived value rather than a stored flag is the design decision worth taking away. values[f] !== opened[f] answers per field, for free, and the third assertion is what a stored flag gets wrong: a user who types a character and deletes it has changed nothing, but a dirty = true set on first keystroke never comes back down, and the "unsaved changes" prompt that follows is a lie.

Validating on every change while showing errors only for touched fields separates two things that get conflated. The state always knows whether the form is valid — which is what the submit button needs — while the display stays quiet until the user has actually visited a field. Submit is then nothing more than "touch everything", which is why one line reveals every outstanding error and why the sixth assertion works without a second validation pass.

The last assertion is the reducer contract. Returning state unchanged for an action you do not handle keeps referential equality, which is what lets a UI skip a re-render. Returning { ...state } instead is a new object every time, every component re-renders, and the bug looks like a performance problem rather than a mistake in the default case.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.