Dpedrinha
Dpedrinha

Reputation: 4220

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

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.

Upvotes: 6

Views: 5499

Answers (3)

Achintha Isuru
Achintha Isuru

Reputation: 3307

  1. For restricting both trailing and leading spaces
TextField(
  controller: yourTextController,
  inputFormatters: [
    FilteringTextInputFormatter.deny(RegExp(r'^\s+|\s+$')),
  ],
)
  1. For restricting only leading spaces
TextField(
  controller: yourTextController,
  inputFormatters: [
    FilteringTextInputFormatter.deny(RegExp(r'^\s+')),
  ],
)

Upvotes: 0

Sumeet.Jain
Sumeet.Jain

Reputation: 1609

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('[ ]')),
                  ]
    );

Upvotes: 15

David L.
David L.

Reputation: 852

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.)

Upvotes: 2

Related Questions