9

I´m trying to only allow numbers and points on a text form field.

I have something like that

WhitelistingTextInputFormatter(RegExp("\d*[.]\d*"))

But does not work, so: Anybody have idea how can only allow digits and point?

El Hombre Sin Nombre
  • 2,906
  • 18
  • 49
  • 92

1 Answers1

21

Since WhitelistingTextInputFormatter is deprecated in Flutter as of 1.20, FilteringTextInputFormatter can be used:

A TextInputFormatter that prevents the insertion of characters matching (or not matching) a particular pattern.

Instances of filtered characters found in the new TextEditingValues will be replaced with the replacementString which defaults to the empty string.

Since this formatter only removes characters from the text, it attempts to preserve the existing TextEditingValue.selection to values it would now fall at with the removed characters.

Example use:

TextField(
 keyboardType: TextInputType.numberWithOptions(decimal: true),
 inputFormatters: <TextInputFormatter>[
      FilteringTextInputFormatter.allow(RegExp(r'^\d+(?:\.\d+)?$')),
  ], 
),

Legacy answer

WhitelistingTextInputFormatter "creates a formatter that allows only the insertion of whitelisted characters patterns". It means your pattern should just match any 1 digit or 1 dot.

Also, you need to use a raw string literal if you want to use a single backslash with regex escapes.

Use

WhitelistingTextInputFormatter(RegExp(r"[\d.]"))

Note that if you want to validate the whole input sequence you need to define a validator: validateMyInput and then add

String validateMyInput(String value) {
    Pattern pattern = r'^\d+(?:\.\d+)?$';
    RegExp regex = new RegExp(pattern);
    if (!regex.hasMatch(value))
      return 'Enter Valid Number';
    else
      return null;
  }

Adapted from Form Validation in Flutter.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • WhitelistingTextInputFormatter is deprecated, you should use FilteringTextInputFormatter (FilteringTextInputFormatter.allow for WhitelistingTextInputFormatter replacement ) – Elias Teeny Sep 18 '20 at 08:55
  • 1
    The answer seems incorrect: `FilteringTextInputFormatter.allow` accepts a regexp for a single character, not an expression for the entire input like `^\d+(?:\.\d+)?$`. – porton Sep 24 '22 at 06:46