Home > Software engineering >  Allow to enter only number 1 to 49 in the TextField in Flutter
Allow to enter only number 1 to 49 in the TextField in Flutter

Time:12-05

I have a TextFiled in a Flatter app and I need it to only be able to enter a number from 1 to 49. Thanks in advance for all the tips.

TextField(
  controller: TextEditingController()
    ..text = (quantity ?? "").toString()
    ..selection = TextSelection.collapsed(offset: (quantity ?? "").toString().length),
   inputFormatters: <TextInputFormatter>[
    LengthLimitingTextInputFormatter(2),
    FilteringTextInputFormatter.digitsOnly,    
  ],
  enabled: true,
),

CodePudding user response:

To restrict the values that can be entered into a TextField in a Flutter app to only numbers from 1 to 49, you can use a WhitelistingTextInputFormatter and specify the allowed characters as a regular expression. Here is an example of how you could do this:

TextField(
  controller: TextEditingController()
    ..text = (quantity ?? "").toString()
    ..selection = TextSelection.collapsed(offset: (quantity ?? "").toString().length),
  inputFormatters: <TextInputFormatter>[
    // Limit the input to 2 characters.
    LengthLimitingTextInputFormatter(2),
    // Only allow digits to be entered.
    FilteringTextInputFormatter.digitsOnly,
    // Only allow numbers from 1 to 49 to be entered.
    WhitelistingTextInputFormatter(RegExp("^([1-9]|[1-4][0-9]|49)$")),
  ],
  enabled: true,
),

In the code above, I have added a WhitelistingTextInputFormatter to the `inputFormatters

CodePudding user response:

Thanks Rahul and Yeasin, your solution works great for me!

  • Related