0
0
Fluttermobile~20 mins

Form validation rules in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Form Validation
A screen with a form that validates user input for email and password fields. It shows error messages if inputs are invalid and a success message when the form is submitted correctly.
Target UI
-------------------------
| Simple Form Validation |
-------------------------
| Email:                |
| [____________________]|
| (error message here)  |
| Password:             |
| [____________________]|
| (error message here)  |
|                       |
| [ Submit ]            |
-------------------------
Two TextFormFields: one for email, one for password
Email field must check for valid email format
Password field must check for minimum 6 characters
Show error messages below each field if invalid
Submit button validates the form and shows a SnackBar with success message if valid
Starter Code
Flutter
import 'package:flutter/material.dart';

class SimpleFormValidation extends StatefulWidget {
  @override
  State<SimpleFormValidation> createState() => _SimpleFormValidationState();
}

class _SimpleFormValidationState extends State<SimpleFormValidation> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Simple Form Validation')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              // TODO: Add Email TextFormField with validation
              // TODO: Add Password TextFormField with validation
              // TODO: Add Submit ElevatedButton
            ],
          ),
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter/material.dart';

class SimpleFormValidation extends StatefulWidget {
  @override
  State<SimpleFormValidation> createState() => _SimpleFormValidationState();
}

class _SimpleFormValidationState extends State<SimpleFormValidation> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();

  String? _validateEmail(String? value) {
    if (value == null || value.isEmpty) {
      return 'Please enter your email';
    }
    final emailRegex = RegExp(r'^[\w-.]+@[\w-]+\.[a-z]{2,}$', caseSensitive: false);
    if (!emailRegex.hasMatch(value)) {
      return 'Enter a valid email address';
    }
    return null;
  }

  String? _validatePassword(String? 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;
  }

  void _submit() {
    if (_formKey.currentState?.validate() ?? false) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Form submitted successfully!')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Simple Form Validation')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _emailController,
                decoration: const InputDecoration(
                  labelText: 'Email',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.emailAddress,
                validator: _validateEmail,
              ),
              const SizedBox(height: 12),
              TextFormField(
                controller: _passwordController,
                decoration: const InputDecoration(
                  labelText: 'Password',
                  border: OutlineInputBorder(),
                ),
                obscureText: true,
                validator: _validatePassword,
              ),
              const SizedBox(height: 20),
              Center(
                child: ElevatedButton(
                  onPressed: _submit,
                  child: const Text('Submit'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }
}

This Flutter screen uses a Form widget with a GlobalKey to manage validation state. It has two TextFormField widgets:

  • The email field uses a regular expression to check if the input looks like a valid email address.
  • The password field checks if the input is at least 6 characters long.

If either field is invalid, an error message appears below it. When the user taps the Submit button, the form validates all fields. If all are valid, a SnackBar shows a success message.

This approach helps users fix mistakes before submitting, making the app friendlier and more reliable.

Final Result
Completed Screen
-------------------------
| Simple Form Validation |
-------------------------
| Email:                |
| [user@example.com   ] |
|                       |
| Password:             |
| [••••••••••••••••••] |
|                       |
|                       |
|       [ Submit ]       |
-------------------------
User types email and password
If input is invalid, error messages appear below fields
Tapping Submit validates inputs
If valid, a SnackBar appears with 'Form submitted successfully!'
Stretch Goal
Add a toggle icon to show or hide the password text
💡 Hint
Use a boolean state variable to switch obscureText on the password TextFormField and an IconButton inside the field's suffixIcon