So i am making a chat app and i want user to submit username which should not be uppercase and have space, i can accept the name and change it later in onchanged feature but i want user to know it as well
3 Answers
Flutter's TextField
or TextFormField
has attribute named inputFormatters
which takes a list of TextInputFormatter
.
an example of TextInputFormatters
that is useful in your case.
FilteringTextInputFormatter.allow(RegExp("[a-z]"))
TextField(
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp("[a-z]")),
],
)
you can see TextInputFormatters
API docs here : Reference
(before flutter 1.20):
WhitelistingTextInputFormatter(RegExp("[a-z]")),
TextField(
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter(RegExp("[a-z]")),
],
)
you can take those as reference if it's not clear enough : Reference 2, Reference 3.
Also check out this SOF Question: Reference 4

- 1,234
- 2
- 13
- 28
-
Thank you very much @Saifallak, even if I searched for something total different. But one hint: 'WhitelistingTextInputFormatter' is deprecated and shouldn't be used. Use FilteringTextInputFormatter.allow instead. This feature was deprecated after v1.20.0-1.0.pre. – Jakob Kühne Aug 15 '20 at 08:43
-
1@Jakob Kühne , thanks for the correction, i will update my answer for future viewers! – Saifallak Aug 16 '20 at 06:05
In regards to changing the text, try doing the following:
Let's say 's' is the username:
String s = ""
onChange(val) {
s = val.trim().toLowerCase()
}
If you want to notify the user, perhaps use an alert dialog with some text letting them know the username should not be uppercase and contain no spaces. Regardless, you can't assume the user will conform to what they "should do".

- 197
- 1
- 9
You can use a Form
and then notify the user using the error field (Validator)
TextFormField(
validator: (name) {
Pattern pattern = r'^[a-z]+$'; // Regex for lowercase only
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(name))
return 'Username must be lowercase, this will be changed when saved';
else
return null;
},
),
FlatButton(
child: Text('Save'),
onPressed: () {
_formKey.currentState.validate(); // just check if its valid and notify user
// Other code to save the and change the value
print('Saving Username');
},
)

- 3,397
- 2
- 25
- 58