JavaScript lesson · 20 min

JavaScript Form Validation

Check form-like data, collect friendly error messages, and normalize input before using it.

Code runs locally in your browser

What you will practice

  • Clean form input before validating.
  • Collect validation errors in an array.
  • Return a clear valid/invalid result.

What this means

Form validation means checking whether user input is good enough to continue.

Client-side validation helps users catch mistakes quickly, but important validation must also happen on the server in real apps.

A friendly validation result should explain what is wrong, not just say `invalid`.

If this is your first time seeing this

Validation checks whether input is acceptable before the program uses it.

Good validation messages tell the person what to fix, not just that something is wrong.

Mini glossary

Validation
Checking input against rules.
Normalize
Clean input into a more predictable form before using it.
Error message
A readable explanation of what needs to be fixed.

Example from everyday life

Form validation is like checking a package before shipping it. You make sure the address exists, the box is not empty, and the label is readable before sending it away.

How it works step by step

  1. The code starts with a form-like object.
  2. `trim()` removes accidental spaces from the email.
  3. The code pushes readable messages into an `errors` array when a rule fails.
  4. The form is valid only when the errors array is empty.

Where you will use this

  • A signup form checks email, password length, and required fields.
  • A checkout form checks address and delivery details before payment.
  • An admin form validates tool metadata before publishing a page.

Before you run the code

Do not try to make beginner validation perfect. Start with clear rules, clear messages, and clean input.

Validation is not security by itself. It improves UX, while server-side checks protect the real system.

Common beginner mistakes

  • Only validating in the browser and forgetting server-side validation in real apps.
  • Showing vague messages like `Invalid` instead of useful messages.
  • Validating before trimming spaces, which can reject input for the wrong reason.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingCleans the email input
WaitingReports the form as valid

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Remove the `@` from the email and run the code.
  • Make the password shorter than 8 characters.
  • Set `displayName` to spaces and see the required-field error.