Skip to main content

Mobile Development11 min read

Flutter Form Validation Best Practices

Learn Flutter form validation: Form and TextFormField setup, reusable validators, live feedback, cross-field and async checks, and multi-step forms.

  • #flutter
  • #form-validation
  • #forms
  • #textfield
  • #validation
  • #user-input
Flutter Form Validation Best Practices
Advertisement

Every app has a form somewhere: sign-up, sign-in, checkout, profile settings, a support request. Forms are where users hand your app their data, and validation is what decides whether that moment feels helpful or hostile. A form that rejects a valid email, clears everything on one mistake, or shows a cryptic error will lose users faster than almost any other bug. Good validation is not about catching bad input. It is about guiding a real person to a correct answer with the least friction possible. This guide covers the patterns that scale: the built-in Form widget, reusable validators, live validation that does not annoy, cross-field checks, async checks, and multi-step forms.

What is form validation in Flutter?

Form validation in Flutter is the process of checking each input field against a rule before the form is submitted, using the built-in Form widget, TextFormField widgets, and a GlobalKey<FormState>. Each TextFormField takes a validator callback that returns an error message string when the input is invalid and null when it is valid. Calling validate() on the form state runs every validator at once and returns true only when all of them return null, so a single call tells you whether the whole form is safe to submit. The framework handles the visible part for you: when a validator returns a string, Flutter shows it in red below the field. When it returns null, the error disappears. You do not need a package for any of this; the Form widget, TextFormField, and GlobalKey are all part of the Flutter framework.

How do you validate a form in Flutter?

You validate a form in Flutter by wrapping your fields in a Form widget with a GlobalKey<FormState>, giving each TextFormField a validator, and calling validate() when the user taps submit. The key is what connects the button to the form: without it, there is no way to trigger validation for every field at once. Here is a complete login form that shows the pattern:

final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();

Form(
  key: _formKey,
  child: Column(
    children: [
      TextFormField(
        controller: _emailController,
        keyboardType: TextInputType.emailAddress,
        decoration: const InputDecoration(labelText: 'Email'),
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Enter your email address';
          }
          if (!value.contains('@')) {
            return 'Enter a valid email address';
          }
          return null;
        },
      ),
      TextFormField(
        controller: _passwordController,
        obscureText: true,
        decoration: const InputDecoration(labelText: 'Password'),
        validator: (value) {
          if (value == null || value.length < 8) {
            return 'Password must be at least 8 characters';
          }
          return null;
        },
      ),
      ElevatedButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            // Every field is valid: submit the form.
            _submit();
          }
        },
        child: const Text('Sign in'),
      ),
    ],
  ),
)

Three details matter here. First, always dispose your TextEditingController objects in the dispose method of a StatefulWidget, or the form will leak memory. Second, validate() returns a bool, so the submit handler reads naturally as an if statement. Third, set keyboardType on each field: TextInputType.emailAddress shows the @ key, and TextInputType.phone shows the number pad, which removes a whole class of input errors before validation ever runs.

When should validation run: on submit or as the user types?

Validation should run on submit first, and then live as the user fixes their input, which is exactly what AutovalidateMode.onUserInteraction does. The Form widget takes an autovalidateMode property with three values, and choosing the wrong one is the most common validation mistake in Flutter apps.

AutovalidateModeBehaviourWhen to use it
disabledValidators run only when you call validate()The default; good for short forms validated on submit
onUserInteractionValidators run after the user edits a field, then on every changeThe best default for most forms
alwaysValidators run on every rebuild, including before the user types anythingRarely; it shows errors on a form nobody has touched yet
Advertisement

AutovalidateMode.always is the trap. It runs every validator the moment the form appears, so a brand-new sign-up screen opens with red errors under empty fields. That reads as a broken app, not a helpful one. onUserInteraction avoids the problem: nothing is checked until the user touches a field, and once they have, errors update live as they type. Pair it with a validate() call in the submit handler, so untouched fields are still checked when the user tries to continue.

How do you write a good validator function?

A good validator function is a small, pure function that takes a nullable string, returns null when the value is valid, and returns one specific, actionable error message when it is not. Keep each validator focused on one rule, keep it reusable, and never put side effects such as network calls or state updates inside it, because Flutter can call validators during a rebuild.

String? validateEmail(String? value) {
  if (value == null || value.isEmpty) {
    return 'Enter your email address';
  }
  final emailPattern = RegExp(r'^[^@]+@[^@]+\.[^@]+$');
  if (!emailPattern.hasMatch(value)) {
    return 'Enter a valid email address';
  }
  return null;
}

String? validatePassword(String? value) {
  if (value == null || value.isEmpty) {
    return 'Enter a password';
  }
  if (value.length < 8) {
    return 'Password must be at least 8 characters';
  }
  return null;
}

Write validators as top-level functions or static methods so several screens can share them, and write them so they can be unit-tested without a widget: pass a string in, get a string or null back. For the messages themselves, name the field and say what a correct value looks like: "Enter a valid email address" helps, "Invalid input" does not. Resist the perfect email regex; a simple pattern that catches missing @ signs and missing domains is enough, because the real proof that an email address works is a confirmation message, not a regular expression.

How do you validate fields that depend on each other?

Fields that depend on each other are validated by reading the other field's controller inside the validator, because a validator only receives its own value. The classic case is a confirm-password field: its validator compares its own value against the password controller's current text.

TextFormField(
  controller: _confirmPasswordController,
  obscureText: true,
  decoration: const InputDecoration(labelText: 'Confirm password'),
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Confirm your password';
    }
    if (value != _passwordController.text) {
      return 'Passwords do not match';
    }
    return null;
  },
)

There is one catch: when the user edits the password field after the confirm field already shows an error, the confirm field does not re-validate on its own, because its own value has not changed. Fix that by re-validating the form when the first field changes, using onChanged on the password field to call _formKey.currentState!.validate() once the form has already been validated at least once. The same pattern works for any dependent pair: a start date and an end date, a minimum and a maximum price, or a country field and a postal-code field whose format depends on it.

How do you show errors without annoying users?

You show errors without annoying users by being specific, placing the message next to the field that caused it, and never clearing the form when validation fails. Flutter's default error display already does the placement part: the message appears directly under its field in red, which is where the user's eyes already are. Keep the submit button enabled and let validate() decide. Disabling the button until the form is valid sounds tidy, but it leaves users tapping a dead button with no explanation of what is wrong. A tap that produces clear, field-level errors is far more helpful than a button that does nothing. Never clear a field's content because it failed validation, and never reset the whole form on a failed submit: the user typed that data, and making them type it again is the fastest way to make them leave. If a submission fails for a server-side reason, such as an email address that is already registered, show that message near the relevant field and keep every value the user entered.

Advertisement

A color-only error is invisible to users with color-vision differences, so pair the red border with the text message, which Flutter does by default. If your app supports more than one language, keep every validation string in your localization files rather than hardcoding English in the validators; see Flutter Localization: Multi-Language Apps.

How do you handle async validation?

Async validation, such as checking whether a username or email address is already taken, cannot run inside a validator, because validators are synchronous and must return immediately. Run the check separately instead: listen to the field with onChanged, debounce the input so you do not fire a request on every keystroke, and store the result in state that the validator then reads.

bool _isUsernameTaken = false;

TextFormField(
  decoration: const InputDecoration(labelText: 'Username'),
  onChanged: (value) {
    // Debounce in real code; simplified here for clarity.
    _checkUsernameAvailable(value);
  },
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Choose a username';
    }
    if (_isUsernameTaken) {
      return 'That username is already taken';
    }
    return null;
  },
)

_checkUsernameAvailable calls your API and updates _isUsernameTaken with setState, then re-validates the form so the message appears or clears. Show a small loading indicator while the check runs, and always re-check on the server when the form is finally submitted: a username that was free a second ago can be taken by the time the user taps submit, so the client-side check is a convenience, not a guarantee.

How do you validate forms across multiple steps?

Multi-step forms are validated one step at a time, with one Form widget and one GlobalKey<FormState> per step, and the user only advances when the current step validates. Keep all the controllers in the parent widget so the data survives moving between steps, and validate each step in its own "Continue" button.

final _stepOneKey = GlobalKey<FormState>();
final _stepTwoKey = GlobalKey<FormState>();

void _goToNextStep() {
  if (_stepOneKey.currentState!.validate()) {
    setState(() => _currentStep += 1);
  }
}

This structure has two advantages over a single giant form. First, the user sees only the errors for the step they are on, instead of a wall of red at the bottom of a long page. Second, each step can be submitted independently, so a user who abandons step three has still given you valid data from steps one and two. If you need to move between steps with a page swipe, use a PageView with swipe gestures disabled and drive the page from your own buttons, so the user can never swipe past an unvalidated step. For guidance on moving between screens once a form is complete, see Flutter go_router: The Navigation Guide.

Common form validation mistakes in Flutter

MistakeWhat happensFix
AutovalidateMode.alwaysErrors show before the user types anythingUse onUserInteraction
Validators with side effectsNetwork calls or state updates run during rebuildsKeep validators pure; do async checks outside them
Generic error messagesUsers do not know what to fixName the field and the expected format
Disabling the submit buttonUsers tap a dead button with no explanationKeep it enabled and let validate() report errors
Clearing fields on failed validationUsers retype data they already enteredKeep all values and show field-level errors
Forgetting to dispose controllersMemory leaks on every form visitDispose every controller in dispose()
No keyboard typeUsers fight the wrong keyboard for emails and numbersSet keyboardType on every field
Form layout matters too: on small screens, fields need room to breathe and error text must not push the submit button off-screen. Wrap the form in a scrollable view and test on a small device. See Flutter Responsive Design for Every Screen for the layout patterns that keep forms usable at any size.

Wrapping up

Form validation in Flutter is mostly a matter of using what the framework already gives you: a Form with a GlobalKey, small pure validators that return null or one clear message, AutovalidateMode.onUserInteraction for live feedback, and validate() on submit as the final gate. Cross-field checks read the other field's controller, async checks live outside the validator, and multi-step forms validate one step at a time. Get those patterns right and your forms stop being a source of support tickets and start being the quiet, helpful part of your app. If your app's forms, onboarding flow, or validation logic need a careful pass from someone who has shipped them in production, Get in touch and let's talk about your project.

Frequently asked questions

How do you validate a form in Flutter?
Wrap your fields in a Form widget with a GlobalKey<FormState>, give each TextFormField a validator, and call validate() when the user taps submit. validate() runs every validator and returns true only when all of them return null.
Which AutovalidateMode should I use in Flutter?
Use AutovalidateMode.onUserInteraction for most forms. It checks nothing until the user touches a field and then updates errors live as they type. Avoid AutovalidateMode.always, which shows errors on a form nobody has touched yet.
Can a Flutter validator make a network call?
No. Validators are synchronous and must return immediately, so they cannot make network calls. Run async checks such as username availability separately with onChanged, store the result in state, and have the validator read that state.
How do you validate a confirm password field in Flutter?
Read the password field's controller inside the confirm field's validator and compare the two values. If they differ, return an error such as 'Passwords do not match'. Re-validate the form when the password field changes so the confirm error clears promptly.

Written by Muhammad Uzair

Flutter Developer & Mobile Engineering Team Lead.

Work with me
Advertisement
All articles
  • Mobile Development

    6 min read

    Flutter ZIP-Code Autofill That Just Works

    Add ZIP-code autofill to your Flutter app: string-safe validation, debounced lookups, stale-response cancellation, and defensive parsing from a production app.

  • Mobile Development

    10 min read

    Flutter Dark Mode: ThemeMode Done Right

    Learn how to add dark mode to a Flutter app the right way: ThemeMode, matching light and dark themes, a switch that remembers its choice, and readable colors.

  • Mobile Development

    10 min read

    Flutter Responsive Design for Every Screen

    Learn how to build Flutter layouts that adapt to phones, tablets and desktops: breakpoints, LayoutBuilder, MediaQuery and flexible widgets that scale.