Skip to the solution
MediumFrontend7 min read

Build a Form Validation Utility Supporting Field-Level and Cross-Field Rules

1.1k views

The problem

Problem, as an interviewer would state it: "Build a form validation utility supporting both per-field rules (required, min length) AND cross-field rules (like confirming two password fields match)."

Examples:

Code
validator.validate({ password: "abc12345", confirmPassword: "different" });
// { valid: false, errors: { confirmPassword: "Passwords do not match" } }

Clarifying questions expected:

  • If a field already has its own field-level error, should a cross-field rule involving that same field still be allowed to overwrite it?
  • Should field-level rules stop at the FIRST failing rule per field, or collect every failing rule's message?
  • Should validation run eagerly (on every keystroke) or only on submit — and does that change this utility's own design?

Code / implementation expected: Yes — real, direct proof of field-level errors, a cross-field mismatch error, a fully valid case, and the subtle precedence case where a cross-field rule must not overwrite an existing field-level error.

  • validation
  • forms

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: field-level and cross-field validation both work correctly, and a cross-field rule does not overwrite an existing field-level error

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 84 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Build a Drift-Corrected Interval Clock (setInterval Alone Drifts Over Time)

Continue