Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Validate a Form

Events & Formsmedium

Course · Section 17: Modern JavaScript Development: Modules, Tooling, and Functional · Lecture 294: Declarative and Functional JavaScript Principles

Controlled forms compute validation errors from current values. Implement `validateForm(form)` for `{ email, password }`: add `email: 'Invalid email'` if the email lacks an `@`, and `password: 'Too short'` if the password is shorter than 6 characters. Return an errors object with only the failing fields.

Sample tests

Input: validateForm({"email":"a@b.com","password":"secret1"})
Output: {}
Input: validateForm({"email":"nope","password":"123"})
Output: {"email":"Invalid email","password":"Too short"}

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Always setting both keys (even to empty strings) makes it impossible to tell valid from invalid by key presence.
  • Checking password <= 6 off-by-one rejects a valid 6-character password.

Learning resources

  • React: Reacting to Input with State
Approach & explanation (try first)

Validation derives an errors map from the current form values. Each rule adds its key only on failure, so an empty object signals a valid form and the UI can show messages just for the keys present.

Loading...
⌘/Ctrl + Enter

Run your code to see results.