I have a text field where I want to limit the user input for a range. e.g. I want the day of the month input in the text field so it should be limited for the range 1 - 31. How can I achieve this in the text field? I can't find any argument to set this.
CodePudding user response:
For the day of month, you can use regular expression
TextFormField(
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp("^(3[01]|[12][0-9]|[1-9])\$")),
],
),
CodePudding user response:
TextEditingController _controller = new TextEditingController();
String text = "";
int maxLength = 2;
new TextField(
keyboardType: TextInputType.number,
controller: _controller,
onChange: (String newVal) {
var num = int.parse(newVal);
if(newVal.length <= maxLength && num > 0 && num < 32){
text = newVal;
}else{
_controller.value = new TextEditingValue(
text: text,
selection: new TextSelection(
baseOffset: maxLength,
extentOffset: maxLength,
affinity: TextAffinity.downstream,
isDirectional: false
),
composing: new TextRange(
start: 0, end: maxLength
)
);
_controller.text = text;
}
}
);
CodePudding user response:
please try this
new TextFormField(
validator: (value) {
if (value==null) {
return '* Please enter Contact No.';
}else if (value.length>10||value.length<10){
return '* Phone number must be 10 digit';
}
return null;
},
style: formText,
maxLength: 10,
controller: _primaryContactController,
keyboardType: TextInputType.phone,
decoration: LeadInputDecoration.textFieldStyle(
labelTextStr: 'Contact No.'),
)