70Build a controlled form with dynamic validation
mediumAbout 40 minutesCodingreactformsvalidationaccessibility
Problem
Build <SignupForm onSubmit={onSubmit} />, a controlled form with these fields (each <input> or <select> has the given name and a matching <label>):
| Field | name | Rule |
|---|---|---|
email |
required, must look like an email | |
| Password | password |
at least 8 characters, with at least one number |
| Confirm password | confirmPassword |
must equal password |
| Account type | accountType |
a <select>: personal (default) or business |
| Company name | company |
only shown, and required, for business |
Error messages are rendered in an element with id="{name}-error", and the field gets aria-invalid="true" and aria-describedby="{name}-error".
- Show a field's error only after it has been touched (blurred) or after a submit attempt; once shown, update it live as the user types.
- On submit with errors, show every error, focus the first invalid field, and do not call
onSubmit. - On a valid submit, call
await onSubmit(values), wherevaluescontainsemail,password,accountTypeand, for business accounts only,company. Disable the submit button while it runs and show a server error inrole="alert"if it rejects.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
values holds every field; touched records which fields were blurred; submitted records whether the user tried to submit. A single handleChange(event) updates values[event.target.name].
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.