D
BLoC PatternMedium30 XP4 min read

How do you implement form validation with Bloc?

TL;DR: Model each form field as a Formz input with pure/dirty validation. Each field change dispatches an event. The Bloc recomputes form validity from all field states and emits updated FormState with field validity + submission status.

Full Answer

The formz package provides a structured way to model form inputs. Each input has a pure() state (pristine, no error shown) and a dirty state (user has interacted, errors visible).

formz approach

  • Create input classes extending FormzInput<T, E>
  • Implement validator() to return an error enum or null
  • Bloc state holds each FormzInput field
  • On field change event: emit new state with dirty input
  • Form is valid when Formz.validate([...allInputs]) returns true

Code Examples

dartEmail + password form with Formz
Output
// Email.dirty('bad') -> EmailError.invalid
// isValid: false until both fields pass validation

Common Mistakes

  • Validating on every keystroke without debouncing — triggers flickers; validate on dirty state only
  • Not using Formz.validate() — manually checking each field.isValid is error-prone

Interview Tip

💡

Show the pure vs dirty distinction — errors only show after user interaction (dirty). This prevents showing 'email required' before the user has even typed.

#form-validation#formz#input-validation#bloc