Reputation: 1787
I have 3 TextFormField
s for inputting of telephone numbers on a Flutter Form
(daytime, evening and mobile).
Validation for each TextFormField
(in the validator:
) allows a blank string to be input.
But I don't want the form to be saved unless there is at least one phone number entered.
formKey.currentState.validate
will obviously validate all individual fields as being valid.
So is there a simple way in the framework to cross validate all the TextFormFields
and display an error without having to write individial validators for each TextFormField
and include references to specific fieldnames (which I regard as being a bit of a dirty hack) e.g.
String _validatePhoneNumber(String value) {
// dirty bit - means I have to write a separate validator for each TextFormField rather than use a generic validator
if (value.isEmpty && this.eveningNumber.isEmpty && this.mobileNumber.isEmpty)
return 'At least one number must be included';
if (value.isEmpty) return null;
if (_invalidNumber(value))
return 'Enter a valid phone number';
return null;
}
Upvotes: 0
Views: 418
Reputation: 441
You should add a TextEditingController
to each TextFormField
, that way you can check the value of each field when you submit your form.
For example:
class MyForm extends StatefulWidget {
@override
_MyFormState createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
final _formKey = GlobalKey<FormState>();
TextEditingController first = TextEditingController();
TextEditingController second = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Form(
key: _formKey,
child: ListView(
children: <Widget> [
TextFormField(
controller: firstController
// rest of your stuff
)
// rest of your text fields using subsequent controllers
// secondController, thirdControler...
]
)
)
)
}
}
Then whenever you want to check it's value you just call firstController.text
or better if you want to know if it's empty you just call firstController.text.isEmpty
Upvotes: 1