🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEreact

react Documentation

LOADING ENGINE...

Form Validation

AI & DATA SCIENCE // form-validation

Form validation checks user input against required rules, like a non-empty field or a valid email format, showing feedback and preventing submission when invalid.

Syntax

const errors = validate(formValues);
if (Object.keys(errors).length === 0) { /* submit */ }

Deep Dive Course

Validation logic typically runs either on every change for immediate feedback, on blur when a field loses focus, or on submit as a final check before actually sending the data — a common pattern computes an errors object mapping each invalid field's name to its specific error message, checked before allowing the actual form submission logic to proceed. While validation can be written entirely by hand with plain functions and conditionals, dedicated libraries like Formik or React Hook Form, often paired with a schema-validation library like Yup or Zod, handle much of this boilerplate, including tracking touched fields and displaying errors at the right time, more consistently than typical hand-rolled solutions.

1Understanding Form Validation

Validation logic typically runs either on every change for immediate feedback, on blur when a field loses focus, or on submit as a final check before actually sending the data — a common pattern computes an errors object mapping each invalid field's name to its specific error message, checked before allowing the actual form submission logic to proceed. While validation can be written entirely by hand with plain functions and conditionals, dedicated libraries like Formik or React Hook Form, often paired with a schema-validation library like Yup or Zod, handle much of this boilerplate, including tracking touched fields and displaying errors at the right time, more consistently than typical hand-rolled solutions.

💡

Validating only on submit, rather than on change or blur, can leave a user staring at a wall of error messages all at once after filling out an entire form — validating on blur, when a field loses focus, generally strikes a better balance between helpful, timely feedback and not being overly aggressive while the user is still actively typing.

editor.html
function validate(values) {
  const errors = {};
  if (!values.email) errors.email = 'Email is required';
  else if (!/\S+@\S+\.\S+/.test(values.email)) errors.email = 'Email is invalid';
  return errors;
}

console.log(validate({ email: 'not-an-email' }));
localhost:3000

2Practical Example

Here is a real-world application of Form Validation showing how it is used in production React code.

editor.html
console.log(validate({ email: '' }));
console.log(validate({ email: 'ana@example.com' }));
localhost:3000

3Best Practices

Follow these guidelines when working with Form Validation:

1. Compute an errors object mapping field names to specific, clear error messages, checking it's empty before allowing actual form submission to proceed

2. Validate on blur for the best balance of timely feedback without interrupting the user while they're still actively typing into a field

3. Reach for a library like Formik or React Hook Form, often paired with Yup or Zod for schema validation, once a form's validation needs grow non-trivial, rather than hand-rolling increasingly complex validation logic

⚠️

Tip: Validating only on submit, rather than on change or blur, can leave a user staring at a wall of error messages all at once after filling out an entire form — validating on blur, when a field loses focus, generally strikes a better balance between helpful, timely feedback and not being overly aggressive while the user is still actively typing.

editor.html
function validate(values) {
  const errors = {};
  if (!values.email) errors.email = 'Email is required';
  else if (!/\S+@\S+\.\S+/.test(values.email)) errors.email = 'Email is invalid';
  return errors;
}

console.log(validate({ email: 'not-an-email' }));
localhost:3000

Examples

Example 01Basic Usage
function validate(values) {
  const errors = {};
  if (!values.email) errors.email = 'Email is required';
  else if (!/\S+@\S+\.\S+/.test(values.email)) errors.email = 'Email is invalid';
  return errors;
}

console.log(validate({ email: 'not-an-email' }));
Example 02Advanced Example
console.log(validate({ email: '' }));
console.log(validate({ email: 'ana@example.com' }));

Best Practices

  • Compute an errors object mapping field names to specific, clear error messages, checking it's empty before allowing actual form submission to proceed
  • Validate on blur for the best balance of timely feedback without interrupting the user while they're still actively typing into a field
  • Reach for a library like Formik or React Hook Form, often paired with Yup or Zod for schema validation, once a form's validation needs grow non-trivial, rather than hand-rolling increasingly complex validation logic

Interview Question

Why is validating a field specifically when it loses focus (on blur) often considered a better default than validating on every single keystroke?

Hint: Think about what an error message looks like while a user is still in the middle of typing a value like an email address.

Validating on every single keystroke means a field like an email input would show an invalid-email error the moment the user types the first character, well before they've had any chance to actually finish typing a complete, valid value, which produces a distracting, discouraging wall of error messages appearing and disappearing constantly while the user is still in the middle of legitimately typing. Validating on blur instead waits until the user has actually finished interacting with that specific field, moved their focus elsewhere, before running the check, which is a much more natural point to judge whether what they entered is genuinely complete and valid, since they've signaled they're done with that field for now. This timing strikes a better balance between giving genuinely useful, timely feedback, rather than waiting all the way until a final submit attempt, and not being so aggressive that it interrupts and discourages the user mid-input for no real benefit.

Exercises

MediumPractice using Form Validation in a real scenario.
View Solution
function validate(values) {
  const errors = {};
  if (!values.email) errors.email = 'Email is required';
  else if (!/\S+@\S+\.\S+/.test(values.email)) errors.email = 'Email is invalid';
  return errors;
}

console.log(validate({ email: 'not-an-email' }));

Frequently Asked Questions

Why is validating a field specifically when it loses focus (on blur) often considered a better default than validating on every single keystroke?

Validating on every single keystroke means a field like an email input would show an invalid-email error the moment the user types the first character, well before they've had any chance to actually finish typing a complete, valid value, which produces a distracting, discouraging wall of error messages appearing and disappearing constantly while the user is still in the middle of legitimately typing. Validating on blur instead waits until the user has actually finished interacting with that specific field, moved their focus elsewhere, before running the check, which is a much more natural point to judge whether what they entered is genuinely complete and valid, since they've signaled they're done with that field for now. This timing strikes a better balance between giving genuinely useful, timely feedback, rather than waiting all the way until a final submit attempt, and not being so aggressive that it interrupts and discourages the user mid-input for no real benefit.

Related Functions

form-handlingformikreact-hook-form