Reputation: 540
I want to trim text on TextFormField on value change, for user to input name. User only allowed to type full name, without extra whitespaces between words. (e.g : Myname Isromeo)
I have already using TextEditingController but still not working properly. Here my snippet code to achieve my goal
final myController = TextEditingController();
...
return new TextFormField(
onChanged: (value){
myController..text = value.trim()
..selection = TextSelection.collapsed(offset: myController.text.length);
},
controller: myController,
keyboardType: TextInputType.phone,
style: FormStyles.inputStyles(),
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xFFCACCCF))),
hintText: 'hint',
contentPadding: EdgeInsets.only(bottom: 8),
hintStyle: FormStyles.hintStyles(),
enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xFFCACCCF)),),
errorStyle: FormStyles.errorStyles(),
),
);
The code above working fine if I only type whitespace, but after I type whitespace after first word, the cursor move to first character. Any suggestion?
Thanks in advance!
Upvotes: 3
Views: 3339
Reputation: 540
So I got my own solution, maybe not the best, but at least it works perfectly!
I decided to create my own input formatter and using RegExp
to achieve my goal.
Here my custom formatter
class NameInputFormatter extends TextInputFormatter{
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
if(newValue.text.length > 0){
TextEditingValue textEditingValue = newValue.copyWith(
text: newValue.text.replaceAll(new RegExp(r"\s+"), ' ')
);
return TextEditingValue(
text: textEditingValue.text,
selection: TextSelection.collapsed(
offset: textEditingValue.text.length,
),
);
}
return newValue;
}
}
If you have better solution, please let me know. Thanks!
Upvotes: 2
Reputation: 14315
You can use BlacklistingTextInputFormatter
for input text as you want ignore with RegExp
.
TextFormField(
decoration: InputDecoration(
labelText: "Title",
),
inputFormatters: [
BlacklistingTextInputFormatter(RegExp("[ ]"))
],
)
For more you can refer this : https://api.flutter.dev/flutter/services/TextInputFormatter-class.html
Upvotes: 5