I'm making a custom TextFormField Widget which will be used multiple times. How do I validate a single TextFormField without validating any other TextFormField that are in the same list/row/column.
Widget timeTextField (TextEditingController controller){
return TextFormField(
controller: controller,
validator: (String userInput){
if(userInput.isEmpty){return 'Need to input time';}
},
onFieldSubmitted: (String userInput){
setState(() {
debugPrint(userInput);
controller.text = "amout";
debugPrint(controller.text);
});
},
);
}
It validates when the user presses submit on the keyboard, if the TextFormField is empty it sends a validation error only to that TextFormField which the user pressed submit on.
In this example, learn how to add validation to a form that has a single text field using the following steps: Create a Form with a GlobalKey . Add a TextFormField with validation logic. Create a button to validate and submit the form.
To validate the form, you can use the autovalidate flag and set up a validator for email. There are many options, including regex or manually writing your own checker, but there are also packages available which implement email checking already. For example, https://pub.dev/packages/email_validator.
Validation in TextField
s happen based on the Form
they are placed in (and not Column
or Row
or List
). To validate TextFields separately put them in different forms, assign different keys and call _formKey.currentState.validate
separately.
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final GlobalKey<FormState> _form1Key = GlobalKey();
final GlobalKey<FormState> _form2Key = GlobalKey();
final GlobalKey<FormState> _form3Key = GlobalKey();
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Form(
key: _form1Key,
child: TextFormField(
validator: (value) {
if (value.isEmpty) return "Cannot be empty";
},
),
),
Form(
key: _form2Key,
child: TextFormField(
validator: (value) {
if (value.isEmpty) return "Cannot be empty";
},
),
),
Form(
key: _form3Key,
child: TextFormField(
validator: (value) {
if (value.isEmpty) return "Cannot be empty";
},
),
),
],
),
floatingActionButton: FloatingActionButton(onPressed: () {
_form2Key.currentState.validate();
}),
);
}
}
Just for information on a closed question:
You can use autovalidateMode
.
This has currently 3 modes. We used to have autovalidate
which is depreciated. This works only on FormFields and inside Forms.
Example
TextFormField(
autocorrect: false,
autovalidateMode: AutovalidateMode.onUserInteraction,
cursorColor: Colors.black,
key: _usernameKey,
Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With