Small details that build taste in Flutter.

curated by Kamran BekirovKamran Bekirov

Limit what users can type in name fields

A name field accepts everything by default: digits, a 500 character paste, double spaces. Filter these while the user types, instead of showing errors after submit:

TextField(
  maxLength: 50,
  inputFormatters: [
    // No digits.
    FilteringTextInputFormatter.deny(
      RegExp('[0-9]'),
    ),
    // No leading space.
    FilteringTextInputFormatter.deny(
      RegExp(r'^\s'),
    ),
    // Collapse double spaces into one.
    FilteringTextInputFormatter.deny(
      RegExp(r'\s\s'),
      replacementString: ' ',
    ),
  ],
  textCapitalization: .words,
  keyboardType: .name,
  autofillHints: const [
    AutofillHints.givenName,
  ],
  autocorrect: false,
  enableSuggestions: false,
  decoration: const InputDecoration(
    labelText: 'First name',
    // Hide the "0/50" counter.
    counterText: '',
  ),
)

What each line does:

  • maxLength: 50 stops long pastes. The backend has a length limit anyway, so stop it in the field.
  • deny removes digits as they are typed. (Don't do allowing only [a-zA-Z]. That blocks letters like ş, ə, é, the apostrophe in O'Brien, the hyphen in double surnames)
  • Don't block spaces, some names have one, like "Ayşe Gül". But block the leading space, allow only one space at a time, and trim() on save.
  • textCapitalization: .words turns on the shift key before each word. The user can still turn it off and type "de Jong". So don't capitalize with a formatter or on save, that would break "de Jong".
  • keyboardType: .name and autofillHints give the right keyboard and one-tap autofill. For the surname field use AutofillHints.familyName.
  • autocorrect: false and enableSuggestions: false stop the keyboard from changing a typed name into a dictionary word.
Kamran Bekirov
Kamran Bekirov

Want this level of care in your Flutter apps?

Work With Me