How to Validate Text Input Forms in Flutter

We all know the TextField widget is the text input widget in Flutter. But what if you want to show multiple text inputs in your app? You can use Form widget for that.

The Form widget groups multiple form widgets and acts as a container. It makes validation of each form field widget easy. In this Flutter, let’s see how to validate forms.

Following is the complete Flutter example to validate forms.

import 'package:flutter/material.dart';


class FormExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Flutter Form Example';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: MyForm(),
      ),
    );
  }
}

// Create a Form widget.
class MyForm extends StatefulWidget {
  @override
  MyFormState createState() {
    return MyFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyFormState extends State<MyForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child:  Padding(
        padding: const EdgeInsets.all(16.0),
        child:Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          TextFormField(
            validator: (value) {
              if (value.isEmpty) {
                return 'Please enter valid name';
              }
              return null;
            },
          ),
          TextFormField(
            validator: (value) {
              if (!value.contains('@')) {
                return 'Please enter valid email';
              }
              return null;
            },
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: RaisedButton(
              onPressed: () {
                // Validate returns true if the form is valid, or false
                // otherwise.
                if (_formKey.currentState.validate()) {
                  // If the form is valid, display a Snackbar.
                  Scaffold.of(context)
                      .showSnackBar(SnackBar(content: Text('Validation Success!')));
                }
              },
              child: Text('Submit'),
            ),
          ),
        ],
      ),
      ),
    );
  }
}

Every form must need a form key to validate its children. The key can be generated using GlobalKey class. Inside Form widget we use TextFormField widget for each text inputs.

Each TextFormField widget has a validator property which is used for the validation purposes. In the above example, we have two inputs and two validations. One field is validated for empty whereas the other for email. We validate the fields only when the submit button is pressed.

Following is the output of Flutter form validation example.

flutter form validation example

I hope you liked this Flutter tutorial. Thank you for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *