Reputation: 3884
The requirement for Regex:
I have tried to generate regex for the same on RegExr and it satisfied my requirements but when I applied the same for the flutter form TextFormField it not working.
Regex: ^[[0-9]{0,8}(\.[0-9]{1,4})?$|^[[0-9]{0,9}(\.[0-9]{1,3})?$|^[[0-9]{0,10}(\.[0-9]{1,2})?$|^[[0-9]{0,11}(\.[0-9]{1})?$|^[0-9]{0,12}
Flutter TextFieldCode:
TextFormField(
controller: _textEditingController,
keyboardType:TextInputType.numberWithOptions(decimal: true),
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter(RegExp(r'^[[0-9]{0,8}(\.[0-9]{1,4})?$|^[[0-9]{0,9}(\.[0-9]{1,3})?$|^[[0-9]{0,10}(\.[0-9]{1,2})?$|^[[0-9]{0,11}(\.[0-9]{1})?$|^[0-9]{0,12}')),
],
),
Using the above code I am not able to type dot(.)
inside the TextFormField.
Note: Users should not be able to enter the number more than one decimal point in the TextFormField
.
Upvotes: 2
Views: 6433
Reputation: 393
Worked for me!
inputFormaters:[FilteringTextInputFormater.allow(RegEx("[0-9.]"))]
Upvotes: 1
Reputation: 626738
Note that if you want to validate the whole input sequence you need to define a validator: validateMyInput
and then implement the function:
String validateMyInput(String value) {
RegExp regex = new RegExp(r'^(?=\D*(?:\d\D*){1,12}$)\d+(?:\.\d{1,4})?$');
if (!regex.hasMatch(value))
return 'Enter Valid Number';
else
return null;
}
See more details at Form Validation in Flutter.
The regex is
^(?=\D*(?:\d\D*){1,12}$)\d+(?:\.\d{1,4})?$
See its demo. Details
^
- start of string(?=\D*(?:\d\D*){1,12}$)
- one to twelve digits required in the string\d+
- 1 or more digits(?:\.\d{1,4})?
- an optional sequence of a .
and then 1, 2, 3 or 4 digits$
- end of string.Upvotes: 6