This is the code for the textformfield I want to restrict. Users should only be able to enter values from 1-10 but I cant find how to implement that
TextFormField(
validator: (value) {
if (value.isEmpty) {
return 'Please enter the Overall Rating';
}
return null;
},
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
maxLength: 2,
maxLengthEnforced: true,
controller: overall,
decoration: InputDecoration(
hintText: "Overall Rating Out of /10",
),
),
CodePudding user response:
you can update your validator function as follows
validator: (value) {
if (value.isEmpty) {
return 'Please enter the Overall Rating';
}
if(value < 1 || value > 10) {
return 'The rating must be between 1 and 10';
}
return null;
},
CodePudding user response:
you can try with form and for digit validation, you need to parse the string to int
Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
// Only numbers can be entered
maxLength: 2,
maxLengthEnforced: true,
controller: overall,
decoration: InputDecoration(
hintText: "Overall Rating Out of /10",
),
validator: (text) {
if (text == null || text.isEmpty) {
return 'Text is empty';
}
if (int.parse(text) < 1 || int.parse(text) > 10) {
return 'The rating must be between 1 and 10';
}
return null;
},
),
TextButton(
onPressed: () {
if (_formKey.currentState.validate()) {
// TODO submit
}
},
child: Text('Submit'),
)
],
),
)