Form Validation in Flutter (Step-by-Step Guide)

In this guide, we’ll walk through a step-by-step process to implement form validation in Flutter, using a practical example.

You can follow the official documentation to set up Flutter.

Forms are fundamental to many mobile applications, allowing users to input data such as usernames, passwords, and email addresses.

In Flutter, a popular framework for building cross-platform mobile apps, form validation ensures that the data entered by users meets specific criteria before submission.

Setting Up the Environment:

Before implementing, ensure you have Flutter SDK installed on your system. You can follow the official documentation to set up Flutter: Flutter Installation Guide.

form validation in Flutter

Creating the Flutter Project:

Begin by creating a new Flutter project using the following command:

flutter create form_validation_app
cd form_validation_app

Implementing Form Validation in Flutter

Now, let’s implement form validation in Flutter using a sample login form. Open the lib/main.dart file in your preferred code editor and replace its contents with the following code:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CustomHomePage(),
      theme: ThemeData(
        brightness: Brightness.dark,
      ),
    );
  }
}

class CustomHomePage extends StatefulWidget {
  @override
  _CustomHomePageState createState() => _CustomHomePageState();
}

class _CustomHomePageState extends State<CustomHomePage> {
  var _formKey = GlobalKey<FormState>();
  var isLoading = false;

  void _submit() {
    final isValid = _formKey.currentState!.validate();
    if (!isValid) {
      return;
    }
    _formKey.currentState!.save();
    // Handle form submission
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Custom Form Validation"),
        leading: Icon(Icons.filter_vintage),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              Text(
                "Custom Form Validation In Flutter",
                style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.width * 0.1,
              ),
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'E-Mail',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.emailAddress,
                onFieldSubmitted: (value) {
                  //Validator
                },
                validator: (value) {
                  if (value!.isEmpty ||
                      !RegExp(
                              r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
                          .hasMatch(value)) {
                    return 'Enter a valid email!';
                  }
                  return null;
                },
              ),
              SizedBox(
                height: MediaQuery.of(context).size.width * 0.1,
              ),
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Password',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.emailAddress,
                onFieldSubmitted: (value) {},
                obscureText: true,
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Enter a valid password!';
                  }
                  return null;
                },
              ),
              SizedBox(
                height: MediaQuery.of(context).size.width * 0.1,
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.symmetric(
                    vertical: 10.0,
                    horizontal: 15.0,
                  ),
                ),
                onPressed: () => _submit(),
                child: Text(
                  "Submit",
                  style: TextStyle(
                    fontSize: 24.0,
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

About Code

  • We start by defining a Flutter app with a dark theme in the MyApp class.
  • The CustomHomePage the class represents the main page of our app, which extends StatefulWidget.
  • Inside _CustomHomePageState, we define a form using Form widget, and we handle form submissions in _submit() method.
  • TextFormField widgets are used for email and password inputs with respective validation functions.
  • Upon clicking the submit button, _submit() the function is triggered, which validates the form fields.
if (value!.isEmpty ||
    !RegExp(
        r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
        .hasMatch(value)) {
  return 'Enter a valid email!';
}

This condition is used to validate whether the provided email address (value) is valid or not. Let’s go through each part of the condition:

  1. value!.isEmpty: This part checks if the value is empty or not. The ! operator negates the result of isEmpty(), so if value is not empty, this part evaluates to false. If value is empty, it evaluates to true.
  2. RegExp(...): This part creates a regular expression object used for pattern matching. Regular expressions are a powerful tool for pattern matching in strings.
  3. The provided regular expression pattern checks if the email address matches the standard email format. Let’s break down the pattern:
    • ^: Asserts the start of the string.
    • [a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_{|}~]+: Matches one or more characters that can be any alphanumeric character, dot (.), or special characters commonly found in email addresses like !, #, $, %`, etc.
    • @: Matches the “@” symbol.
    • [a-zA-Z0-9]+: Matches one or more alphanumeric characters for the domain name before the dot.
    • \.: Matches the dot (.) character.
    • [a-zA-Z]+: Matches one or more alphabetical characters for the top-level domain (TLD).
    • $: Asserts the end of the string.
  4. .hasMatch(value): This part checks if the regular expression pattern matches the value (the email address). If there’s a match, it returns true; otherwise, it returns false.

So, putting it all together:

  • If value is empty (value!.isEmpty evaluates to true), or
  • If value does not match the regular expression pattern for a valid email address (!RegExp(...).hasMatch(value) evaluates to true), the condition returns true, indicating that the email address is not valid.

In such cases, the function returns the message 'Enter a valid email!', indicating to the user that the provided email address is not in the correct format. Otherwise, if both conditions are false, the function returns null, indicating that the email address is valid.

Output:

Output of Custom Form Validation in Flutter

Also Read:

Conclusion

Form validation is crucial for ensuring data integrity and enhancing user experience in Flutter applications. By following the steps outlined in this guide, you can easily implement form validation in your Flutter projects. Remember to adapt the validation criteria according to your specific application requirements.

Share:
Ambika Dulal

Ambika Dulal is a Flutter Developer from Nepal who is passionate about building beautiful and user-friendly apps. She is always looking for new challenges and is eager to learn new things. She is also a strong believer in giving back to the community and is always willing to help others.

Leave a Comment

AO Logo

App Override is a leading mobile app development company based in Kathmandu, Nepal. Specializing in both Android and iOS app development, the company has established a strong reputation for delivering high-quality and innovative mobile solutions to clients across a range of industries.

Services

UI/UX Design

Custom App Development

Mobile Strategy Consulting

App Testing and Quality Assurance

App Maintenance and Support

App Marketing and Promotion

Contact

App Override

New Plaza, Kathmandu