Frontend Patterns

Pattern

Form-Level Validation

Validate entire forms on submission to check cross-field rules and constraints.

State Management Intermediate

Form-Level Validation

Problem

Some validation rules depend on multiple fields working together - like ensuring a password confirmation matches, checking that a date range is valid, or verifying that at least one contact method is provided. Individual field validation can’t catch these cross-field constraints, allowing users to submit forms with logically inconsistent data that only becomes apparent when all fields are considered together.

Solution

Validate entire forms after users complete them to check cross-field rules and complex constraints. This complements field-level validation by catching issues that require seeing the whole picture.

Example

This example demonstrates validating cross-field rules that require examining multiple form fields together, such as password confirmation and date range validation.

function validateForm(data) {
  const errors = {};

  // Cross-field validation: Check if passwords match
  if (data.password !== data.confirmPassword) {
    errors.confirmPassword = 'Passwords must match';
  }

  // Cross-field validation: Check if date range is valid
  if (new Date(data.endDate) < new Date(data.startDate)) {
    errors.endDate = 'End date must be after start date';
  }

  return errors;  // Return all form-level validation errors
}

Benefits

  • Catches cross-field validation issues that single field validation cannot detect.
  • Enables complex business rules that depend on multiple values working together.
  • Provides a final validation checkpoint before submission to prevent invalid data.
  • Complements field-level validation for comprehensive form validation coverage.

Tradeoffs

  • Delays validation feedback until the user completes the entire form.
  • Can be frustrating if users must fix errors after filling out the whole form.
  • May duplicate validation logic if the same rules are checked at field and form level.
  • Requires careful UX design to communicate form-level errors effectively.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.