skip to Main Content

In this following code, I limit the input range to English characters. But if I input non-English characters (e.g. Chinese characters), the textfield would clear.

TextField(
          maxLines: null,
          style:
              const TextStyle(fontSize: 18, fontWeight: FontWeightExt.regular),
          inputFormatters: [
            /// Input only english character (contains english symbol).
            FilteringTextInputFormatter.allow(
                RegExp(r'^(?:[a-zA-Z]|P{L})+$', unicode: true)),
      
          ],
          decoration: InputDecoration(
              border: InputBorder.none,
              hintText: UserIntl.feedbackContactTextFieldHint,
              hintStyle: const TextStyle(
                fontSize: 15,
                color: ColorsExtension.tGray2,
                fontWeight: FontWeightExt.regular,
              ),
              contentPadding:
                  const EdgeInsets.only(top: 13, bottom: 13, left: 16)),
          onChanged: (inputText) => onTextChanged.call(inputText),
        )

I expected the textfield to only input English characters. But inputting non-English characters does not cause the text to be cleared.

2

Answers


  1. hey if you want to only allow English characters (letters and symbols) in the TextField, you can update the regular expression as follows:

    FilteringTextInputFormatter.allow(RegExp(r'^[a-zA-Zs]+$')),
    
    Login or Signup to reply.
  2. The issue is that the regular expression you are using to filter the input only allows English letters and symbols. When a non-English character is entered, it does not match the regex, so the input formatter clears the entire text field.

    To fix this, you need to update the regex to allow all unicode characters, not just English letters.

    You can use this regex:

    r'^[p{L}p{N}p{P}p{Zs}]+$'
    

    This allows letters (p{L}), numbers (p{N}), punctuation (p{P}), and whitespace (p{Zs}) from any unicode script.

    So your code would be:

    inputFormatters: [ FilteringTextInputFormatter.allow(RegExp(r'^[p{L}p{N}p{P}p{Zs}]+$', unicode: true)) ],
    

    Now it should allow non-English characters without clearing the text field

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search