2

I have a simple TextField where the user should not be allowed to type in leading whitespaces. I found a couple of similar answers about removing whitespaces from Strings or don't allow any whitespaces. But in my case the only restriction should be leading whitespaces.

This is what I found for TextFields but that is removing all whitespaces.

Can anyone help me out here?

Chris
  • 1,828
  • 6
  • 40
  • 108

3 Answers3

3

Create your own TextInputFormatter and change returned value of formatEditUpdate(...).

Sample:

class NoLeadingSpaceFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    if (newValue.text.startsWith(' ')) {
      final String trimedText = newValue.text.trimLeft();

      return TextEditingValue(
        text: trimedText,
        selection: TextSelection(
          baseOffset: trimedText.length,
          extentOffset: trimedText.length,
        ),
      );
    }

    return newValue;
  }
}

Usage:

TextField(
  inputFormatters: [
    NoLeadingSpaceFormatter(),
  ],
),
rickimaru
  • 2,275
  • 9
  • 13
1

No leading whitespace regex is

^\S
^(?!\s)

In Dart, do not forget to use raw string literals, r"^\S" or r"^(?!\s)".

See the regex demo.

Details

  • ^\S - any non-whitespace char (\S) at the start of string
  • ^(?!\s) - a start of string (^) position that cannot be immediately followed with a whitespace ((?!\s) is a negative lookahead).
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

You can use the trimRight() method:

The string without any trailing whitespace.

As trim, but only removes trailing whitespace.

void main() {
 print('\t Space\t. Dart is fun\t\t'.trimRight()); // '  Space  . Dart is fun'
}
MendelG
  • 14,885
  • 4
  • 25
  • 52