You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中FilteringTextInputFormatter输入非法字符后文本清空问题

解决TextField输入非法字符时清空文本的问题

问题根源

你写的正则r'^(?:[a-zA-Z]|\P{L})+$'加了^和$,要求整段输入完全符合规则。一旦输入汉字这类非法字符,整个字符串不匹配规则,FilteringTextInputFormatter.allow就会把所有内容清空。

修复代码

把正则里的^和$去掉,改成匹配单个允许的字符,这样formatter会自动过滤非法字符,同时保留合法的现有内容:

TextField(
          maxLines: null,
          style:
              const TextStyle(fontSize: 18, fontWeight: FontWeightExt.regular),
          inputFormatters: [
            /// 仅允许输入英文字符及英文符号
            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),
        )

额外说明

  • \P{L}是Unicode正则语法,用来匹配所有非字母类的字符,也就是各种英文符号,刚好满足你要包含英文符号的需求。
  • 如果想更精准控制允许的符号,直接枚举就行,比如把\P{L}换成`!@#$%^&*(),.?":{}|<>这类你需要的符号集合。

内容的提问来源于stack exchange,提问作者Drown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 17:42:09