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.