Flutter Form Validation (A Basic Guide)

When developing mobile applications with flutter, one of the most common requirements is handling form data submissions and validating user input. Get an insight on how to efficiently validate forms in flutter with code examples.

Flutter Form Validation

Form validation ensures that the data user has entered is correct and complete before processing and submitting the form. Besides data integrity form validation also ensures that invalid or malicious data is not submitted to back-end and provides a better user experience. In this post we will explore how to perform flutter form validation with some real code examples.

 

How to Validate Forms in Flutter (Form, TextFormField, FormState, TextEditingController)

Flutter provides an easy to validate form fields using Form, TextFormField and FormState along with TextEditingController for every field in form. We will create a stateful flutter widget BasicForm and validate email and password field. The code can be explained as:

  • Create a StatefulWidget with BasicForm name.
  • Add a GlobalKey variable _formKey for our FormState which is used to identify and manage the state of form.
  • Add TextEditingController variables _emailController and _passwordController for email and password field.
  • In build of widget use the flutters Form widget and assign the _formKey to identify form.
  • Add two fields using TextFormField widget, one for email and other for password.
  • Assign the _emailController to controller parameter of email field.
  • Assign _passwordController to controller parameter of password field.
  • Implement validation logic in function assigned to validator parameter of both fields. Both fields are required i.e. should not be empty. The email field implement regular expression check whereas password field implement minimum 6 characters required logic.
  • Add a form submission button using ElevatedButton widget of flutter.
  • Check the state of form in function assigned to onPressed parameter of ElevatedButton widget.
class BasicForm extends StatefulWidget {
@override
_BasicFormState createState() => _BasicFormState();
}

class _BasicFormState extends State<BasicForm> {
// This key will identify the form
final _formKey = GlobalKey<FormState>();

// Controllers to retrieve values from text fields
final _emailController = TextEditingController();
final _passwordController = TextEditingController();

@override
Widget build(BuildContext context) {
return Form(
key: _formKey, // Key to access form state
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller: _emailController,
decoration: InputDecoration(labelText: 'Email'),
keyboardType: TextInputType.emailAddress,
// Validator for email
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter an email';
}
if (!RegExp(r"^[a-zA-Z0-9]+@([a-zA-Z0-9]+\.)+[a-zA-Z]{2,}$").hasMatch(value)) {
return 'Please enter a valid email address';
}
return null; // No error
},
),
TextFormField(
controller: _passwordController,
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
// Validator for password
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a password';
}
if (value.length < 6) {
return 'Password must be at least 6 characters';
}
return null; // No error
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid
if (_formKey.currentState!.validate()) {
// Form is valid
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Processing Data')),
);
}
},
child: Text('Submit'),
),
),
],
),
);
}
}
In addition to above explained code, following are the key points that must be followed for smooth flutter form validation and user experience.
  • Always use GlobalKey<FormState> to manage the state and validate form.
  • Use the validator property for built-in validation like empty fields, emails, and passwords.
  • For custom logic, advanced validation rules can be created using regex or compare fields.
  • Show a notification via Snackbar or AlertDialog to user whether form submission was successful or not.

We demonstrated a basic flutter form validation with code example. Flutter makes it easy to create and validate form using built-in Form and TextFormField widgets. The example above can be further customized based on flutter application requirements.