Sanskar Tiwari
Sanskar Tiwari

Reputation: 37

Allow Only lowercase with no space Input Textfield Flutter

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

Upvotes: 4

Views: 9476

Answers (3)

Saifallak
Saifallak

Reputation: 1339

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

Upvotes: 11

Tinus Jackson
Tinus Jackson

Reputation: 3653

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');

                    },
                  )

Dart Pad Example

Upvotes: 1

eandpi
eandpi

Reputation: 237

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".

Upvotes: 1

Related Questions