Back to Articles

Beginner

Form Validation and TextFormField in Flutter

· 7 min read

Form and GlobalKey<FormState>

A Form widget groups several TextFormFields together and lets you validate all of them at once through a formKey. Each field keeps running its own validator, but the form gives you one place to trigger and check them all.

final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: Column(
    children: [
      TextFormField(
        decoration: const InputDecoration(labelText: 'Email'),
        validator: _validateEmail,
      ),
      TextFormField(
        decoration: const InputDecoration(labelText: 'Password'),
        obscureText: true,
        validator: _validatePassword,
      ),
    ],
  ),
)

The validator Function

Every TextFormField takes a validator: it receives the current text and returns either null (the field is valid) or a String that's shown as the error message right under the field. Keep each validator focused on one field — combine multiple checks inside it rather than spreading the logic across the widget tree.

String? _validateEmail(String? value) {
  if (value == null || value.isEmpty) {
    return 'Email cannot be empty';
  }
  final emailRegex = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+
  
  


);
  if (!emailRegex.hasMatch(value)) {
    return 'Enter a valid email';
  }
  return null; // valid
}

String? _validatePassword(String? value) {
  if (value == null || value.length < 6) {
    return 'Password must be at least 6 characters';
  }
  return null;
}

Validating the Form: validate()

formKey.currentState!.validate() runs every field's validator at once and returns true only if all of them pass. It also makes Flutter redraw each field, so any error message appears immediately — this is the call you put behind your submit button.

ElevatedButton(
  onPressed: () {
    if (_formKey.currentState!.validate()) {
      // All fields are valid, proceed with submission
      _submit();
    }
  },
  child: const Text('Submit'),
)

autovalidateMode: Instant Feedback

By default a field's error only shows up after validate() runs once. Setting autovalidateMode: AutovalidateMode.onUserInteraction on the Form re-runs validators as the user types, after their first interaction with each field — so mistakes are flagged before they even reach the submit button.

Form(
  key: _formKey,
  autovalidateMode: AutovalidateMode.onUserInteraction,
  child: TextFormField(
    validator: _validateEmail,
    onChanged: (_) {}, // the validator re-runs on every keystroke
  ),
)

Chaining Fields with FocusNode

A FocusNode per field plus textInputAction: TextInputAction.next lets the keyboard's 'next' button jump straight to the following field instead of closing the keyboard. Call requestFocus() on the next field's FocusNode from onFieldSubmitted, and finish the chain with TextInputAction.done on the last field.

final _emailFocus = FocusNode();
final _passwordFocus = FocusNode();

TextFormField(
  focusNode: _emailFocus,
  textInputAction: TextInputAction.next,
  onFieldSubmitted: (_) => _passwordFocus.requestFocus(),
  validator: _validateEmail,
),
TextFormField(
  focusNode: _passwordFocus,
  textInputAction: TextInputAction.done,
  onFieldSubmitted: (_) => _submit(),
  validator: _validatePassword,
),

Wiring the Submit Button to the Form

Calling setState() on every keystroke just to enable or disable a submit button rebuilds the whole form unnecessarily. A lighter approach is a ValueNotifier<bool> updated from the Form's onChanged callback, read by a ValueListenableBuilder that wraps only the button.

final _isValid = ValueNotifier<bool>(false);

Form(
  key: _formKey,
  onChanged: () {
    _isValid.value = _formKey.currentState?.validate() ?? false;
  },
  child: Column(
    children: [
      // ... TextFormFields
      ValueListenableBuilder<bool>(
        valueListenable: _isValid,
        builder: (context, isValid, _) {
          return ElevatedButton(
            onPressed: isValid ? _submit : null,
            child: const Text('Submit'),
          );
        },
      ),
    ],
  ),
)

Things to Watch Out For

1. Localize Your Error Messages

Validator messages are text the user actually reads, so they shouldn't be hardcoded strings — route them through your app's localization (AppLocalizations) just like any other visible text.

2. Don't Forget to Dispose

TextEditingControllers and FocusNodes created in initState must be released in dispose(), or you leak them every time the form's widget is torn down.

Conclusion

Form and GlobalKey<FormState> turn a group of independent fields into one unit you can validate, submit and give feedback on together. Keep validators focused and localized, use autovalidateMode for a friendlier typing experience, chain fields with FocusNode, and always dispose what you created.