im trying to make a calculator app and I'm trying to set some validation messages for the text fields like "please enetr numbers only" I used formkey to do that but the validation is not working I'm new to dart I couldn't figure what is the issue
this is my code :
final formkey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Container(
padding: new EdgeInsets.all(25.0),
child: Form(
key: formkey,
child: Column(
children: <Widget>[
SizedBox(height: 45),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
"Basic Calculator",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 30),
)
],
),
SizedBox(height: 60),
Row(
children: <Widget>[
const Text(
"First Number",
style: TextStyle(fontWeight: FontWeight.bold),
)
],
),
SizedBox(height: 10),
Row(
children: <Widget>[
new Flexible(
child: new TextFormField(
keyboardType: TextInputType.number,
controller: num1controller,
decoration: InputDecoration(
hintText: "Enter a number",
border: new OutlineInputBorder(
borderSide: new BorderSide(color: Colors.teal)),
),
validator: (value) {
if (value!.isEmpty ||
!RegExp(r'^[,]*[.][0-9] $').hasMatch(value!)) {
return "please enter numbers only";
} else {
return null;
}
},
),
),
],
)
CodePudding user response:
The given code looks fine to me, however, you are missing one thing. You need to call the validate()
method on the currentState
of the form.
Like this formKey.currentState.validate()
. This is needed to be called in order to validate the form.
Alternatively, you can also use autovalidateMode
property of the form field (Not tested though). Like: autovalidateMode: AutovalidateMode.onUserInteraction
. This way you won't need to call the validate
method on the form state.