32

I have a TextField that will only take numbers as an input. The Keyboard that appears allows for the input of the the following characters: "-(hyphen) ,(comma) .(period) and space". How can I prevent the user from entering all except the period.

child: new TextField(
  controller: _controller,
  maxLengthEnforced: true,
  keyboardType: TextInputType.number,
  maxLength: 4, //9999 upper limit
  ), //TextField

I've tried to use RegExp to take the _controller text, remove the characters and place it back into to field without any luck.

...//Add Listener to _controller
_controller.addListener(restrictCharacters);
...

//Listener
void restrictCharacters(){
  RegExp regexp = new RegExp(
    r"^|\-|\,|\ ",
    caseSensitive: false,
    multiLine: false,);
  String text = _controller.text;
  String chng = text.replaceaLL(regExp,"");
  _controller.text = chng;
}

When applied the cursor moves to beginning and the field keeps the - (hyphen) for example.

SupremeAbraxas
  • 321
  • 1
  • 3
  • 3

15 Answers15

80

In your TextInputField(), use a FilteringTextInputFormatter like this:

TextField(
 inputFormatters: <TextInputFormatter>[
      FilteringTextInputFormatter.allow(RegExp("[0-9a-zA-Z]")),
  ], // Only numbers can be entered
),

Each character typed will be allowed only if it matches the RegExp. To include a space, use the regular expression "[0-9a-zA-Z ]" instead. Period means "any character" in regular expressions unless you escape them, like "[0-9\.a-zA-Z]".

.deny can be used in place of .allow to proved a blacklist instead of a whitelist.

Michael Gundlach
  • 106,555
  • 11
  • 37
  • 41
Siddy Hacks
  • 1,846
  • 14
  • 15
18

WhitelistingTextInputFormatter is deprecated. You should use FilteringTextInputFormatter.allow:

inputFormatters: [ FilteringTextInputFormatter.allow(RegExp("[a-zA-Z]")), ]

or FilteringTextInputFormatter.deny instead of BlacklistingTextInputFormatter

David Buck
  • 3,752
  • 35
  • 31
  • 35
Eduardo
  • 475
  • 4
  • 9
11

Add a BlacklistingTextInputFormatter to your TextField.

  inputFormatters: [
    new BlacklistingTextInputFormatter(new RegExp('[\\.]')),
  ],

removes just . If you wanted to disallow, say, . and , change it to

  inputFormatters: [
    new BlacklistingTextInputFormatter(new RegExp('[\\.|\\,]')),
  ],
Richard Heap
  • 48,344
  • 9
  • 130
  • 112
  • Thanks [TextInputFormatter](https://docs.flutter.io/flutter/services/TextInputFormatter-class.html) inputFormatters: [BlacklistingTextInputFormatter(new RegExp(r'[-]|[ ]|[,]'))], – SupremeAbraxas May 21 '18 at 22:35
  • It seems that this not work as intended. [RegExp with multiple groups is not supported.](https://docs.flutter.io/flutter/services/WhitelistingTextInputFormatter/whitelistedPattern.html) – SupremeAbraxas May 22 '18 at 18:33
  • 1
    This is incorrect, you don't need to escape with backslashes. It should be `[.,]`. – Hasen Jul 20 '19 at 06:11
7

Add this to your TextField for letters and numbers

inputFormatters: [new  WhitelistingTextInputFormatter(RegExp("[a-zA-Z0-9]")),],
rhavelka
  • 2,283
  • 3
  • 22
  • 36
7

If you want double to be added,you can also use the format like this:

inputFormatters: [FilteringTextInputFormatter.allow(RegExp("[0-9\.]")),],

Be sure to include the backslash, as a period on its own means "any character" (allowing everything).

Michael Gundlach
  • 106,555
  • 11
  • 37
  • 41
Haileapp
  • 755
  • 7
  • 20
6

Dart 2.13+, Flutter 1.27+

 inputFormatters:[FilteringTextInputFormatter.allow(RegExp('[a-zA-Z0-9]'))]
Kedar Sukerkar
  • 1,410
  • 1
  • 16
  • 22
3

For those who need to work with money format in the text fields:

To use only: , (comma) and . (period)

and block the symbol: - (hyphen, minus or dash)

as well as the: (blank space)

In your TextField, just set the following code:

keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [BlacklistingTextInputFormatter(new RegExp('[ -]'))],

The simbols hyphen and space will still appear in the keyboard, but will become blocked.

Fellipe Sanches
  • 7,395
  • 4
  • 32
  • 33
  • 1
    The regex string could simply be `[ -]`. The escapes are unnecessary, and you're additionally blacklisting the pipe character `|` (which surely isn't an issue but still) – Ricket Mar 17 '19 at 06:31
  • Right, you don't need the backslash escapes. – Hasen Jul 20 '19 at 06:12
1
 inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.allow(RegExp("[0-9a-zA-Z]")),],  
Ravindra S. Patil
  • 11,757
  • 3
  • 13
  • 40
0

if you want to include English and Devanagari character also in your name then follow this regex pattern I have created this pattern for English letter and Devanagari letters with allow space

 inputFormatters: [ WhitelistingTextInputFormatter(RegExp("[a-zA-Z \u0900-\u097F]")),
                    LengthLimitingTextInputFormatter(30),
                  ],
Abhijit Rajmane
  • 173
  • 2
  • 12
0

You can deny special characters with escape sequences or get any escape sequence from google which you want

Example:

inputFormatters: [
                    FilteringTextInputFormatter.deny(
                      RegExp("[a-zA-Z0-9\u0020-\u007E-\u0024-\u00A9]"),
                    ),
                    
                  ],
iknow
  • 8,358
  • 12
  • 41
  • 68
Faizan Ahmad
  • 62
  • 1
  • 5
0

None of the above answers worked for me, This is how to use FilteringTextInputFormatter inside TextFormField:

TextFormField(
  inputFormatters: [
  FilteringTextInputFormatter(
  RegExp("[a-zA-Z]"),
  allow: true),
  ],)

Set allow to false if you want to deny the RegExp.

Vikas
  • 136
  • 6
0

Add this to your TextField for letters and numbers

inputFormatters: [WhitelistingTextInputFormatter(RegExp("[a-zA-Z0-9]")),],
0

First you need to import "services" package.

 import 'package:flutter/services.dart';

Then you can use:

inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r"^|\-|\,|\ "))]
jsonx
  • 1,093
  • 3
  • 14
  • 21
0

Here is the solution I use. You can enter only numbers and only one dot. I think that this is the best solution for the number input field.

inputFormatters: [
      FilteringTextInputFormatter.allow(RegExp(r'[0-9.]')),
      SingleDotFormatter(),
],

class SingleDotFormatter extends TextInputFormatter {
bool hasDot = true;
@override
TextEditingValue formatEditUpdate(
  TextEditingValue oldValue, TextEditingValue newValue) {
if (hasDot && newValue.text.endsWith('.') && newValue.text.split('.').length > 2) {
  return oldValue;
}

if (!hasDot && newValue.text.endsWith('.')) {
  hasDot = true;
  return newValue;
}

if (hasDot && !newValue.text.contains('.')) {
  hasDot = false;
  return newValue;
}

return newValue;
}
}
0

Try this

TextField(
  inputFormatters: [
    FilteringTextInputFormatter.allow(RegExp(r"[a-zA-Z0-9]+|\s")),
  ],
  decoration: InputDecoration( 
    border: OutlineInputBorder(),
    hintText: 'Enter a search term',
  ),
),


  1. FilteringTextInputFormatter.allow: This is an input formatter class provided by Flutter. It allows you to define a regular expression pattern to filter and restrict the input text. In your case, you are using a regular expression that matches alphanumeric characters (letters and digits) along with whitespace characters (\s).

  2. RegExp(r"[a-zA-Z0-9]+|\s"): This is the regular expression pattern that defines what text is allowed to be entered in the text field. Breaking it down:

  • [a-zA-Z0-9]+: This part of the pattern matches one or more alphanumeric characters (letters or digits).
  • |: This is the OR operator in regular expressions.
  • \s: This part of the pattern matches whitespace characters, such as spaces.
Tejaswini Dev
  • 1,311
  • 2
  • 8
  • 20