Flutter-TextFormField中的正则表达式 [英] Flutter - Regex in TextFormField

查看:1011
本文介绍了Flutter-TextFormField中的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试只允许在文本表单字段上输入数字和点.

I´m trying to only allow numbers and points on a text form field.

我有类似的东西

WhitelistingTextInputFormatter(RegExp("\d*[.]\d*"))

但不起作用,因此:任何人都知道如何只允许数字和点?

But does not work, so: Anybody have idea how can only allow digits and point?

推荐答案

从1.20开始,WhitelistingTextInputFormatter 在Flutter中已弃用, FilteringTextInputFormatter 可以使用:

Since WhitelistingTextInputFormatter is deprecated in Flutter as of 1.20, FilteringTextInputFormatter can be used:

用于阻止字符插入的 TextInputFormatter 匹配(或不匹配)特定模式.

A TextInputFormatter that prevents the insertion of characters matching (or not matching) a particular pattern.

在新的 TextEditingValue 中找到的过滤字符实例 将替换为 replacementString ,默认为 空字符串.

Instances of filtered characters found in the new TextEditingValues will be replaced with the replacementString which defaults to the empty string.

由于此格式化程序仅从文本中删除字符,因此它 尝试将现有的 TextEditingValue.selection 保留为值 现在它将与删除的字符交织在一起.

Since this formatter only removes characters from the text, it attempts to preserve the existing TextEditingValue.selection to values it would now fall at with the removed characters.

示例用法:

TextField(
 keyboardType: TextInputType.numberWithOptions(decimal: true),
 inputFormatters: <TextInputFormatter>[
      FilteringTextInputFormatter.allow(RegExp(r'^\d+(?:\.\d+)?$')),
  ], 
),

旧版答案

WhitelistingTextInputFormatter "创建一个格式化程序仅允许插入列入白名单的字符模式" .这意味着您的图案应该与任何1位数字或1个点匹配.

WhitelistingTextInputFormatter "creates a formatter that allows only the insertion of whitelisted characters patterns". It means your pattern should just match any 1 digit or 1 dot.

此外,如果要对正则表达式转义使用单个反斜杠,则需要使用原始字符串文字.

Also, you need to use a raw string literal if you want to use a single backslash with regex escapes.

使用

WhitelistingTextInputFormatter(RegExp(r"[\d.]"))

请注意,如果要验证整个输入序列,则需要定义validator: validateMyInput,然后添加

Note that if you want to validate the whole input sequence you need to define a validator: validateMyInput and then add

String validateMyInput(String value) {
    Pattern pattern = r'^\d+(?:\.\d+)?$';
    RegExp regex = new RegExp(pattern);
    if (!regex.hasMatch(value))
      return 'Enter Valid Number';
    else
      return null;
  }

改编自 Flutter中的表单验证 .

这篇关于Flutter-TextFormField中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆