Reputation: 267
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'^[^\s][a-zA-Z ]')),
],
I tried this regex expression in the TextFormField but it is not taking alphabets also. I want the text field to restrict the space at the beginning but allow in the middle. How to achieve it?
Upvotes: 0
Views: 1068
Reputation: 1389
class CustomFormatter extends TextInputFormatter {
CustomFormatter();
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.isNotEmpty) {
if (newValue.text.length > oldValue.text.length) {
return TextEditingValue(text: newValue.text.trimLeft(), selection: TextSelection.collapsed(offset: newValue.text.trim().isNotEmpty ? newValue.selection.end : 0));
} else {
return newValue;
}
}
return newValue;
}
}
TextField(
inputFormatters: [CustomFormatter()],
),
Upvotes: 1
Reputation: 1932
Your regex only allows one symbol in range of [a-zA-Z]
. To allow multiple symbols you should try this:
RegExp(r'^[^\s][a-zA-Z ]*$')
or shorter:
RegExp(r'^\S[a-zA-Z ]*$')
Upvotes: 0
Reputation: 786
I would use the controller like MyCar said and additionaly put a logic in the onChanged() method of the text field. Then just check if the first character is space and if yes, remove it.
TextFormField(
controller: controller,
onChanged: (value) {
if (value.isNotEmpty) {
if (value[0] == " ") {
controller.text = value.trimLeft();
}
}
},
),
Upvotes: 1
Reputation: 31
just use function
trimLeft()
with your TextEditingController Like this
yourController.text.trimLeft()
Upvotes: 1
Reputation: 4556
You should use TextEditingController
:
final TextEditingController controller = TextEditingController();
TextFormField(
controller: controller,
),
controller.text.trimLeft()
Upvotes: 2