Multi Form Validation — Flutter
This blog is regarding the validation of multiple textformfields.
The demonstration had divided into two parts:
Building UI with a basic form.
Validate the fields.
Building UI with a basic form
This form contains an appbar, four textformfeilds, and a raisedbutton.
Validate the fields
- Declare a variable ‘_key’ as GlobalKey<FormState>, where we use this as a key for Form.
- Declare a variable ‘_autoValidate’ as boolean and assign value equals to false, where we use this to autovalidate the Form.
- Now, add the validations to each textformfield.
_validateName
_validateUserName
_validateAge
_validateBio
All these validations will be different based on textformfeild usage.
Now, we can validate the all textformfields with raisedbutton.
RaisedButton(
color: Colors.blue,
child: Text('Save'),
onPressed: () {
if(_key.currentState.validate()){
showDialog(
context: context,
child: AlertDialog(
title: Text('Validated'),
)
);
}
},
),
When we click the raisedbutton, if all the textformfields are not filled then it returns the validator message.
When you click the save with wrong format input in textformfield it returns the validation message as shown in below image.
When we click the save with correct input, then it validates the textformfields as true and show an alertdialog as ‘Validated’.
In this way we can validate the multiple textformfields.
For GitHub Code — Click Here
If there are any suggetions for better approch to write my next blog. Please let me know!