【问题标题】:Flutter TextField TextInputFormatter wipes whole string on entering not allowed characterFlutter TextField TextInputFormatter 在输入不允许的字符时擦除整个字符串
【发布时间】:2021-06-15 15:08:58
【问题描述】:

所以我有正常的TextField,像这样:

                TextField(
                          autofocus: true,
                          controller: _textController,
                          keyboardType: TextInputType.text,
                          inputFormatters: <TextInputFormatter>[
                            FilteringTextInputFormatter.allow(RegExp(
                                r'^[A-zÀ-ÖØ-öø-įĴ-őŔ-žǍ-ǰǴ-ǵǸ-țȞ-ȟȤ-ȳɃɆ-ɏḀ-ẞƀ-ƓƗ-ƚƝ-ơƤ-ƥƫ-ưƲ-ƶẠ-ỿ\s*&^%0-9,.-:)(]+$')),
                          ],
                          style: TextStyle(
                            color: Colors.amber,
                          ),
                          decoration:
                              InputDecoration(fillColor: Colors.transparent),
                          maxLines: null,
                        ),

一切正常,直到我在字段中写入不允许的字符,然后整个字符串消失。我深入研究并发现FilteringTextInputFormatter.allow 具有称为replacementString 的属性,默认情况下为空字符串。现在的问题是,我应该如何使用它,因为如果我向文本控制器添加一个监听器并监控更改,我不知道用户是否删除了文本或者用户是否输入了不允许的字符。据我所知。

是否有一些方法可以阻止使用 RegEx 输入字符,我不想删除文本,我只想阻止输入不允许的字符。是否有某种方法可以在没有侦听器或其他进行此类检查的方法的情况下实现这一目标?

【问题讨论】:

  • 尝试删除正则表达式末尾的$,同时删除replacementString
  • @Fatimaayaa 好吧,我尝试删除 $,但是 replacementString 无法删除,它是 FilteringTextInputFormatter.allow 的一部分,无论我喜欢与否,它都在那里,只是默认为空字符串。
  • 我尝试在没有replacementString的情况下编译它并且它可以工作oO
  • 我不确定,但这意味着位置就在字符串的最后一个字符之后

标签: regex flutter validation dart


【解决方案1】:

所以解决这个问题的方法很简单,正则表达式末尾不应该有 $ 符号,我正在回答这个问题,以防有人发现这很有用。

而不是这个:

FilteringTextInputFormatter.allow(RegExp(
                                r'^[A-zÀ\s*&^%0-9,.-:)(]+$'))

为了正确的功能,它必须是这样的:

FilteringTextInputFormatter.allow(RegExp(
                                r'^[A-zÀ\s*&^%0-9,.-:)(]+'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 2021-09-25
    • 2016-03-28
    • 1970-01-01
    • 2019-09-30
    相关资源
    最近更新 更多