Form Validation in Flutter with Example

Form validation is an important aspect of building applications with Flutter. It ensures that the data entered by the user is accurate and meets the necessary criteria. In this blog, we'll explore how to perform form validation in Flutter with an example.

First, let's create a basic form with a text field and a button to submit the form.

import 'package:flutter/material.dart';
class FormValidationDemo extends StatefulWidget {
  @override
  _FormValidationDemoState createState() => _FormValidationDemoState();
}
class _FormValidationDemoState extends State<FormValidationDemo> {
  final _formKey = GlobalKey<FormState>();
  String _email;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Form Validation Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              TextFormField(
                keyboardType: TextInputType.emailAddress,
                decoration: InputDecoration(
                  hintText: 'Enter your email',
                ),
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter your email';
                  }
                  if (!RegExp(r'\S+@\S+\.\S+').hasMatch(value)) {
                    return 'Please enter a valid email';
                  }
                  return null;
                },
                onSaved: (value) {
                  _email = value;
                },
              ),
              SizedBox(height: 16.0),
              RaisedButton(
                child: Text('Submit'),
                onPressed: () {
                  if (_formKey.currentState.validate()) {
                    _formKey.currentState.save();
                    _submit();
                  }
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
  void _submit() {
    // Handle form submission
  }
}ā€‹

In this code, we're using the Form widget to create a form with a single TextFormField. The TextFormField is used to capture the user's email address. We're also using the validator property to ensure that the entered email address is valid.

The validator function takes a string as input and returns a string if there's an error, or null if the input is valid. In this case, we're checking if the string is empty or if it doesn't match the regular expression for an email address.

If there are no validation errors, we call the _submit() function to handle the form submission. Otherwise, the user will see an error message indicating that they need to enter a valid email address.

It's important to note that the validator function is only called when the user submits the form. If you want to validate the input as the user types, you can use the autovalidateMode property of the Form widget.

Form(
  key: _formKey,
  autovalidateMode: AutovalidateMode.always,
  child: ...ā€‹

With this property set to AutovalidateMode.always, the validator function will be called whenever the user changes the input value.

In conclusion, form validation is an important aspect of building applications with Flutter. By using the validator property of the TextFormField, we can ensure that the user's input meets the necessary criteria. We can also use the autovalidateMode property of the Form widget to validate the input as the user types.