Flutter: Form Widget and Input Validation
personAhmet Balaman
calendar_today
FlutterFormValidationTextFormFieldWidgetInput
Form is a widget used in Flutter to group input controls and perform validation. With Form, we can manage multiple input fields under a single structure and perform batch validation.
Live Demo
You can try this widget in the interactive example below:
💡 If the example above doesn't load, click DartPad to run it in a new tab.
💡 If the example above doesn't load, you can DartPad to run it in a new tab.
Basic Usage
Form widget is managed with a GlobalKey:
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'This field cannot be empty';
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// Form is valid, perform operation
}
},
child: Text('Submit'),
),
],
),
)TextFormField Properties
TextFormField(
controller: _controller,
decoration: InputDecoration(
labelText: 'Email',
hintText: '[email protected]',
prefixIcon: Icon(Icons.email),
suffixIcon: Icon(Icons.check),
border: OutlineInputBorder(),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
),
validator: (value) => value!.isEmpty ? 'Required field' : null,
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
obscureText: false, // true for password
maxLength: 50,
maxLines: 1,
)Validation Functions
// Email validation
String? validateEmail(String? value) {
if (value == null || value.isEmpty) {
return 'Email is required';
}
final regex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
if (!regex.hasMatch(value)) {
return 'Invalid email format';
}
return null;
}
// Password validation
String? validatePassword(String? value) {
if (value == null || value.length < 6) {
return 'Password must be at least 6 characters';
}
return null;
}Form Methods
| Method | Description |
|---|---|
validate() |
Validates all fields |
save() |
Calls onSaved callbacks |
reset() |
Resets the form |
AutovalidateMode
Form(
key: _formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
// AutovalidateMode.disabled - Manual validation
// AutovalidateMode.always - Always validate
// AutovalidateMode.onUserInteraction - Validate on user interaction
child: ...
)Using onSaved
String? _email;
TextFormField(
onSaved: (value) {
_email = value;
},
)
// When form is submitted
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save(); // Calls onSaved callbacks
print(_email);
}Summary
- Form: Groups input fields
- GlobalKey
: Manages form state - TextFormField: Text input with validation
- validator: Validation function
- validate(): Checks all fields
Form widget is essential for managing user inputs.