Decimal or Signed numeric values in regular expression validation in Flutter
This will work fine. Textfield doesn't become blank, if invalid character is entered.
WhitelistingTextInputFormatter(RegExp(r'(^\-?\d*\.?\d*)')),
sanjay
I am a Android and iOS Developer having 4+ years of experience in software development. Developed IoT apps for Android and iOS platform. In love with Kotlin.
Updated on December 19, 2022Comments
-
sanjay 11 months
I am trying to use a regular expression validation to check for only decimal values or signed numeric values in a Flutter App.
Valid inputs are like
- 12.3
- -12.33
I have used
WhitelistingTextInputFormatter
to restrict the user inputs. Please refer the code below:TextFormField( key: AppKeys.emailField, keyboardType: TextInputType.emailAddress, controller: controller.emailTextController, inputFormatters: [ WhitelistingTextInputFormatter(RegExp(r'[0-9-]\d*(\.\d+)?')), ], maxLength: 100, decoration: InputDecoration( labelText: Strings.emailPrompt, counterText: '', prefixIcon: Icon(Icons.email), ), //validator: Validator.validateEmail, onSaved: (String val) { //_email = val; }, );
But this seems to have not working. Though it's working fine for only numbers it's not accepting dot character. Regex should also accept one minus character that to be at the starting and one dot character that to be in the middle.
Any help is highly appreciate. Thanks in Advance.
-
Wiktor Stribiżew over 3 yearsIt only matches the character typed in, one at a time, right? So,
[0-9-]
only works and this is why the dot is not "allowed". If you replace it with[0-9.-]
, it will. -
sanjay over 3 years@WiktorStribiżew, But in that case it will allow to enter more than one dot and minus character.
-
Wiktor Stribiżew over 3 yearsRight, you can't use what you are using now.
-
sanjay over 3 yearsYes. I need to correct it. But i don't know how to do that.
-
sanjay over 3 yearsHi, thanks for your answer. The above regex works fine but the only problem is when I enter any other character my textfield becomes blank. I don't know why this is happening. It was happening earlier as well when I was trying with the regex I have used. When we use
^
at the start and$
at the then textfield becomes blank if we enter any other character. -
Midhun MP over 3 years@sanjay That's because of entering a wrong character or wrong format. I'll check if there is anyway to avoid that
-
Mahmood Ali over 2 yearsCan you explain why it works without clear the text?
-
Neo over 2 yearsI used it
inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'(^\-?\d*\.?\d*)'))]
and it worked. Many thanks. Could you please also explain it :) -
Ali Abbas over 2 years
WhitelistingTextInputFormatter
is deprecated, instead you can useFilteringTextInputFormatter.allow
please update to help others.