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

Flutter TextField中InputFormatter的使用及两种输入规则配置方法

Using InputFormatter in Flutter TextField: Two Common Use Cases

Hi there! Let's walk through how to work with InputFormatter in Flutter's TextField and solve your two specific input constraints.

What's an InputFormatter?

Put simply, InputFormatter lets you control, filter, or modify the text a user enters into a TextField. Flutter provides a handy built-in class called FilteringTextInputFormatter that covers most basic filtering needs—perfect for your requirements.


1. Prohibit Input of \ and /

To block users from entering backslashes (\) and forward slashes (/), you can use FilteringTextInputFormatter.deny() with a regular expression that targets these characters.

Here's how to implement it:

TextField(
  decoration: InputDecoration(labelText: "No \\ or / allowed"),
  inputFormatters: [
    FilteringTextInputFormatter.deny(RegExp(r'[\\/]')),
  ],
)
  • The regex r'[\\/]' matches both \ (we need to escape it with another backslash in the raw string) and /.
  • FilteringTextInputFormatter.deny() will reject any input that matches this regex.

2. Allow Only Letters (a-z, A-Z)

To restrict input to just uppercase and lowercase letters, use FilteringTextInputFormatter.allow() with a regex that targets alphabetic characters.

Implementation example:

TextField(
  decoration: InputDecoration(labelText: "Only letters (a-z, A-Z)"),
  inputFormatters: [
    FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z]')),
  ],
)
  • The regex r'[a-zA-Z]' matches any uppercase or lowercase letter from A to Z.
  • FilteringTextInputFormatter.allow() will only accept input that matches this regex—all other characters (numbers, symbols, etc.) will be blocked.

Bonus: Custom InputFormatter for Complex Logic

If you ever need more control (like dynamic validation or modifying input instead of just blocking), you can create a custom TextInputFormatter. For example:

class CustomFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    // Add your custom logic here
    final filteredText = newValue.text.replaceAll(RegExp(r'[^a-zA-Z]'), '');
    return TextEditingValue(
      text: filteredText,
      selection: TextSelection.collapsed(offset: filteredText.length),
    );
  }
}

Then use it in your TextField like this:

inputFormatters: [CustomFormatter()],

Hope this helps you get exactly the input behavior you need!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:08:25