Is there a way to automatically remove or avoid leading and trailing spaces in a TextField?

2,161

Solution 1

You can use inputFormatters properties of TextField. It wont allow users to add spaces in textField.

TextField(
        inputFormatters: [
                BlacklistingTextInputFormatter(RegExp('[ ]')),
              ]
);

UPDATE: For flutter version above 1.20.* use this instead

TextField(
            inputFormatters: [
                    FilteringTextInputFormatter.deny(RegExp('[ ]')),
                  ]
    );

Solution 2

If you're fine with the user typing in those spaces but just don't want them to be passed to your processing method, you can either use a validator to display an error message to the user ('no leading/trailing spaces allowed') or you can trim it from the resulting string before processing. You can use a Regex expression to validate emails as well if you want to take the validator approach. You can disable spaces by using an inputFormatter, but keep in mind that will disable all spaces in the TextField, which shouldn't be an issue for an e-mail field but might cause issues elsewhere (name fields, address fields, etc.)

Share:
2,161
Dpedrinha
Author by

Dpedrinha

Updated on December 15, 2022

Comments

  • Dpedrinha
    Dpedrinha over 1 year

    I'm making an email field and I'd like to either avoid or auto-delete leading and trailing spaces in it.

    I tried using

    myTextFieldController.addListener(() { myTextFieldController.text = myTextFieldController.text.trim(); });
    

    but as soon as the user types any character it moves the cursor to the beginning.

    Any other way?

    You know users so I need to remove it or they will stay there forever trying to validate the field.

    Of course I know I can do it before validating but I'd like to know if there's a more robust approach.