Send Clean Values on Submit

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code

ContactForm takes an onSubmit prop. It has text inputs labelled "Name", "Email" and "Age", a checkbox labelled "Send me the newsletter" and a "Send" button. Use a form with noValidate, so both Send and pressing Enter in a field submit it. Clean the values first: trim the name; trim the email and make it lower case; Age is optional, trimmed, and becomes a number, or null when blank; the newsletter is true or false. If the name is blank, show "Enter your name"; if the email has no "@", show "Enter a valid email"; if Age is filled in but isn't a whole number from 0 to 150, show "Enter a whole number for age". With any error, don't call onSubmit. Otherwise call onSubmit once with an object holding exactly name, email, age and newsletter, then clear the form (empty fields, box unticked) and show "Message sent". The preview renders it without onSubmit, so check it's there before calling it.

Your code must pass

  • Sends trimmed, lower-cased and parsed values
  • A blank age is sent as null, and Enter submits
  • Invalid values show errors and send nothing
  • Sending clears the form
  • Fixing the errors lets it send