Home > other >  How to restrict the user from entering space at the beginning in a textfield in flutter?
How to restrict the user from entering space at the beginning in a textfield in flutter?

Time:10-03

inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp(r'^[^\s][a-zA-Z ]')),
              ],

I tried this regex expression in the TextFormField but it is not taking alphabets also. I want the text field to restrict the space at the beginning but allow in the middle. How to achieve it?

CodePudding user response:

You should use TextEditingController:

final TextEditingController controller = TextEditingController();

TextFormField(
  controller: controller,
),

controller.text.trimLeft()

CodePudding user response:

just use function trimLeft() with your TextEditingController Like this

yourController.text.trimLeft()

CodePudding user response:

I would use the controller like MyCar said and additionaly put a logic in the onChanged() method of the text field. Then just check if the first character is space and if yes, remove it.

TextFormField(
  controller: controller,
  onChanged: (value) {
    if (value.isNotEmpty) {
      if (value[0] == " ") {
        controller.text = value.trimLeft();
      }
    }
  },
),

CodePudding user response:

Your regex only allows one symbol in range of [a-zA-Z]. To allow multiple symbols you should try this:

RegExp(r'^[^\s][a-zA-Z ]*$')

or shorter:

RegExp(r'^\S[a-zA-Z ]*$')
  • Related