问题描述
我正在尝试只允许在文本表单字段上输入数字和点.
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:
在新的 TextEditingValue 中找到的过滤字符实例将替换为 replacementString ,默认为空字符串.
Instances of filtered characters found in the new TextEditingValueswill be replaced with the replacementString which defaults to theempty string.
由于此格式化程序仅从文本中删除字符,因此它尝试将现有的 TextEditingValue.selection 保留为值现在它将与删除的字符交织在一起.
Since this formatter only removes characters from the text, itattempts to preserve the existing TextEditingValue.selection to valuesit 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中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!