regex - Flutter - TextFormField 中的正则表达式

标签 regex flutter

我试图只允许在文本表单字段上使用数字和点。

我有这样的东西

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

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

最佳答案

WhitelistingTextInputFormatter自 1.20 起在 Flutter 中已弃用,FilteringTextInputFormatter可以使用:

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

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

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(RegExp(r"[\d.]"))

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

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;
  }

改编自Form Validation in Flutter .

关于regex - Flutter - TextFormField 中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390839/

相关文章:

Javascript 简码解析

javascript - 在 javascript 中执行没有 while 循环条件的组提取?

c# - 正则表达式模式与某些节目标题不匹配

firebase - flutter firebaseauth signout() 不起作用

android-studio - 在 Android Studio 中使用 Flutter 时更改 Auto-Indent Lines 设置

dart - Flutter(Dart)如何在点击应用程序时将副本添加到剪贴板?

java - 空格不匹配

c# - DNA密码变异过程: finding substrings

flutter - 将API中的数据设置为变量-Flutter

dart - 使用 flutter_html_view 插件时如何修复 flutter 中的这个错误