Form Validation in Flutter

Create Free Backend With Appwrite

Form Validation in Flutter

If you are building a form in your Flutter application, it is essential to validate the user input data to ensure data integrity. In this section, you will learn how to validate user input data using the TextFormField widget in Flutter.

Why Form Validation is Important?

  • Data Integrity: It ensures that the data entered by the user is accurate and consistent.
  • User Experience: It provides a better user experience by guiding the user to enter valid data.
  • Error Prevention: It helps in preventing errors and exceptions caused by invalid data.

Example 1: Feedback Form with Validation

In this example, you will learn to create a feedback form with a validation rule ensuring a minimum character count. If you have any problem try Run Online button to see the code in action.

// Create a GlobalKey for the form
final _formKey = GlobalKey<FormState>();

// Create a TextEditingController for the feedback field
final _feedbackController = TextEditingController();

Form(
  key: _formKey,
  child: Column(
    mainAxisSize: MainAxisSize.min,
    children: [
      TextFormField(
        maxLines: 5,
        controller: _feedbackController,
        decoration: const InputDecoration(
          hintText: 'Enter your feedback',
          border: OutlineInputBorder(),
        ),
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Please enter your feedback';
          } else if (value.length < 10) {
            return 'Feedback must be at least 10 characters';
          }
          return null;
        },
      ),
      const SizedBox(height: 20),
      ElevatedButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('Feedback submitted successfully!')),
            );
            // Additional submission logic here
          }
        },
        child: const Text('Submit'),
      ),
    ],
  ),
)
Run Online

Example 2: Sign-Up Form with Validation

In this example, you will learn to create a sign-up form with validation to ensure users provide a valid email address and a secure password. If you have any problem try Run Online button to see the code in action.

// Create a GlobalKey for the form
final _formKey = GlobalKey<FormState>();

// Create TextEditingController for email and password fields
final _emailController = TextEditingController();
final _passwordController = TextEditingController();

Form(
  key: _formKey,
  child: Column(
    mainAxisSize: MainAxisSize.min,
    children: [
      TextFormField(
        controller: _emailController,
        decoration: const InputDecoration(
          labelText: 'Email',
          hintText: 'Enter your email',
          border: OutlineInputBorder(),
        ),
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Please enter your email';
          } else if (!value.contains('@')) {
            return 'Please enter a valid email';
          }
          return null;
        },
      ),
      const SizedBox(height: 10),
      TextFormField(
        controller: _passwordController,
        decoration: const InputDecoration(
          labelText: 'Password',
          hintText: 'Enter your password',
          border: OutlineInputBorder(),
        ),
        obscureText: true,
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Please enter your password';
          } else if (value.length < 6) {
            return 'Password must be at least 6 characters';
          }
          return null;
        },
      ),
      const SizedBox(height: 20),
      ElevatedButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('Sign-up successful!')),
            );
            // Additional submission logic here
          }
        },
        child: const Text('Sign Up'),
      ),
    ],
  ),
)
Run Online

Challenge

Create a contact form with fields name, phone number, and email and validate according to the following rules:

Name: Required
Phone Number: Required, must be 10 digits
Email: Required, must be a valid email address