I am creating a TextField
in flutter, but I want the input to explicitly follow a regex: ^-?d+(.d+)?(-d+)?(e-?d+)?$
(That allows scientific numbers, in which 'e'
is used as powers of ten).
When the user enters a character that makes the input not follow the regex, the character will just not be entered and the valid input that was before remains.
How can I achieve that?
I tried: using inputFormatters: [FilteringTextInputFormatter.allow()]
and other formatters, but I can only set banned or allowed characters, not a whole regex expression.
I searched: stackoverflow, but all answers just give that certain characters are allowed and some aren’t. I haven’t seen anyone validate input by a whole complex regex.
2
Answers
You can try something like this
Below is the link to my code you can test the validation there.
https://zapp.run/edit/flutter-z6606xl6706?split=50&lazy=false&entry=lib/main.dart&file=lib/main.dart
Custom Input Formatter for Regex
You can extend
TextInputFormatter
and then override theformatEditUpdate
method. Inside this method you can check whether the new value matches yourRegex
pattern or not. If it does, you allow the update, else you return the previous value.My Approach:
1. Create Custom Input Formatter:
2. Use this custom input formatter with your TextField:
To ensure that if a user enters a character that would make the entire input not fit the
Regex
pattern, the character won’t be included and the previous correct input will stay as it is.