Hi i am facing this issue where i cant allow the letter x and decimal inputs in the textfield. If removing one of the FilteringTextInputFormatter.allow it will work but having both cause nothing to happen in the textformfield when the user types. How can i configure this to work and to only allow users to key in either numbers or the letter X and not both in the textformfield.
(e.g. numbers such as ( -1 , -1.234 , 10 , 5.8) will be allow. user will also have the choice to type in the letter x or X instead of numbers . However inputs such as (1.2x or 3X) shouldnt be allow. )
Much thanks!
TextFormField(
inputFormatters: [
// deny -. and .number
FilteringTextInputFormatter.deny(RegExp(r'(^\.)')),
FilteringTextInputFormatter.deny(RegExp(r'-\. ')),
//allow decimal ( -) and the letter x
FilteringTextInputFormatter.allow(RegExp(r'(^-?\d*\.?\d*)*$')),
FilteringTextInputFormatter.allow(RegExp(r'[xX]')),
],
onChanged:(value) {
setState(() {
fieldPointX = (value);
});
},
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'X'
),
),
CodePudding user response:
Use both inputFormatters and validator. i made a mistake in inputFormatter that it doesn't accept incomplete input like '-' and '123.' so user couldn't input negative and number that is not integer.
regex in formatter and validator is similar but the difference is inputFormatter use *
(zero or more) instead of
(one or more) for digit and -
.
for more info on validator refer to https://docs.flutter.dev/cookbook/forms/validation
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(r'^-?\d*(?:.\d*)?$|^[Xx]$')),
],
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
if (!RegExp(r'^-?\d (?:.\d )?$|^[Xx]$').hasMatch(value)) {
return 'Invalid input';
}
return null;
},
old answer:
try only this regex
FilteringTextInputFormatter.allow(RegExp(r'^-?\d*(?:.\d*)?$|^[Xx]$'))
^-?\d
take a zero or more number that can start with -
or not
(?:.\d )
non capturing group for number after decimal
|
or operator
^[Xx]$
single X or x
you can try it here https://regex101.com/r/1vinoJ/1