Flutter
validator
Validate a field with the validator callback.
What is validator?
validator is a callback given to a TextFormField. It is called when the user fills the field and returns an error message (String) or null. null means valid.
TextFormField(
validator: (value) {
if (value!.isEmpty) return 'Cannot be empty';
return null;
},
)
The error message appears below the field.
errorText display
The String returned by the validator is shown as errorText under the TextFormField's decoration. Each time the user types, the validator runs again and the error message updates.
validator: (value) {
if (value!.length < 3) {
return 'At least 3 characters';
}
return null;
}
The error message appears in red automatically.
Exercise Empty field check with validator
In Ekrani stateful widget, declare _formKey. Place a TextFormField inside a Form; the validator should return 'Boş bırakılamaz' for empty value. On button press, call _formKey.currentState!.validate() and if the result is true, print 'geçerli'. In main, call print('form hazır').
Show example solution
import 'package:flutter/material.dart';
void main() {
print('form hazır');
runApp(MaterialApp(home: Ekrani()));
}
class Ekrani extends StatefulWidget {
@override
_EkraniState createState() => _EkraniState();
}
class _EkraniState extends State<Ekrani> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (deger) {
if (deger!.isEmpty) {
return 'Boş bırakılamaz';
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('geçerli');
}
},
child: Text('Kontrol et'),
),
],
),
),
),
);
}
}
Test yourself
-
What should the validator callback return for a valid value?
- null
- An error message String
- true
- false
Show answer
null — validator returns null if the value is valid; it returns an error message String if invalid.
-
Return an error message in validator
validator: (deger) {
if (deger!.isEmpty) {
____ 'Boş bırakılamaz';
}
return null;
}
Show answer
validator: (deger) {
if (deger!.isEmpty) {
return 'Boş bırakılamaz';
}
return null;
}
-
validator parts
- validator
- Callback that validates the field
- null dönüşü
- Means the value is valid
- String dönüşü
- Means an error message
- errorText
- Where the error is shown
Next lesson: onSaved