0
0
Fluttermobile~5 mins

Form validation rules in Flutter

Choose your learning style9 modes available
Introduction

Form validation rules help check if the information entered by a user is correct before saving or sending it. This avoids mistakes and keeps data clean.

When asking users to enter their email or phone number to make sure it looks right.
When creating a signup form to ensure passwords are strong and match.
When collecting feedback to make sure required fields are not empty.
When submitting orders to confirm all necessary details are filled in.
When building any form where user input needs to be checked for errors.
Syntax
Flutter
TextFormField(
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Please enter some text';
    }
    return null;
  },
)

The validator function returns a string error message if the input is invalid.

If the input is valid, the validator must return null.

Examples
Checks if the field is empty and shows an error if it is.
Flutter
TextFormField(
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Field cannot be empty';
    }
    return null;
  },
)
Checks if the input contains '@' to validate a simple email format.
Flutter
TextFormField(
  validator: (value) {
    if (value == null || !value.contains('@')) {
      return 'Enter a valid email';
    }
    return null;
  },
)
Ensures the password is at least 6 characters long.
Flutter
TextFormField(
  validator: (value) {
    if (value == null || value.length < 6) {
      return 'Password must be at least 6 characters';
    }
    return null;
  },
)
Sample App

This app shows a form with email and password fields. When you tap Submit, it checks if the email contains '@' and if the password is at least 6 characters. If there are errors, it shows messages below the fields. If all is good, it shows a small message at the bottom saying 'Processing Data'.

Flutter
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Form Validation Example')),
        body: const Padding(
          padding: EdgeInsets.all(16),
          child: MyCustomForm(),
        ),
      ),
    );
  }
}

class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});

  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}

class _MyCustomFormState extends State<MyCustomForm> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextFormField(
            decoration: const InputDecoration(labelText: 'Email'),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your email';
              }
              if (!value.contains('@')) {
                return 'Please enter a valid email';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          TextFormField(
            decoration: const InputDecoration(labelText: 'Password'),
            obscureText: true,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your password';
              }
              if (value.length < 6) {
                return 'Password must be at least 6 characters';
              }
              return null;
            },
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Processing Data')),
                );
              }
            },
            child: const Text('Submit'),
          ),
        ],
      ),
    );
  }
}
OutputSuccess
Important Notes

Always return null from the validator if the input is valid.

You can combine multiple checks inside one validator function.

Use GlobalKey<FormState> to manage the form state and trigger validation.

Summary

Form validation rules check user input and show helpful error messages.

Use the validator property on TextFormField to add rules.

Return a string error message if invalid, or null if valid.