All 7 Forms & Input Validation in Flutter questions
More in Forms & Input Validation in Flutter
Advertisement
Flutter › Forms & Input Validation in Flutter

How does the validator property on a TextFormField let you define a specific custom validation rule, such as properly checking that an entered email address actually contains an genuine at symbol?

Beginner

Answer

The validator property accepts a function that receives the field's own current entered text value and should return either null, indicating that value is genuinely valid, or a specific descriptive error message string if that value is genuinely not actually valid, and Flutter automatically calls this exact same validator function for every single field whenever the surrounding Form's own validate method is actually called, automatically displaying any returned error message directly underneath its own corresponding specific field.
TextFormField(
  validator: (value) {
    if (value == null || !value.contains('@')) {
      return 'Please enter a genuinely valid email address';
    }
    return null;
  },
)
Real-world example A login form's email field displays a clear error message directly underneath it the moment a user attempts to submit the form having entered text that genuinely does not contain the required at symbol, guiding them to properly correct their specific mistake.

Common follow-ups: Can a single field genuinely have more than one separate distinct validation rule applied together?;How do you properly trigger validation to actually happen as a user types, rather than only when they genuinely submit the entire form?