6

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.

Dpedrinha
  • 3,741
  • 3
  • 38
  • 57

2 Answers2

14

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('[ ]')),
                  ]
    );
Sumeet.Jain
  • 1,533
  • 9
  • 26
  • 1
    BlacklistingTextInputFormatter is deprecated after v1.20.0-1.0.pre. Now use FilteringTextInputFormatter.deny(RegExp('[ ]')) instead. – ByronSchuurman Sep 24 '20 at 19:33
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.)

David L.
  • 762
  • 4
  • 7
  • Yes, for now I'm using a validator and trim() before processing it. But I'd like an option more robust. In other words, don't need to remember to check for it in the future and just avoid it completely. – Dpedrinha Nov 27 '19 at 22:54
  • There's no way of doing that automatically, and it wouldn't make sense to me - you can maybe detect the first character being a space, but there's no telling whether the space they just typed will be the last one. Having a listener listen to changes to input and remove spaces accordingly would just remove spaces, period. You can customize your own `TextFormField` so that it comes with the validation and trimming logic out-of-the-box, but that's about it for "do once and forget" approach... or at least I can't think of a way to do it. – David L. Nov 28 '19 at 00:19
  • Problem with the listener is that every time I change the textFieldController.text it moves the cursor to the beginning. I'll try inputFormatters. – Dpedrinha Nov 28 '19 at 01:00