Reputation: 2274
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?
Upvotes: 2
Views: 3137
Reputation: 626738
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).Upvotes: 1
Reputation: 2490
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(),
],
),
Upvotes: 4
Reputation: 20008
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'
}
Upvotes: 0