我试图只允许在文本表单字段上使用数字和点。
我有这样的东西
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;
}
关于regex - Flutter - TextFormField 中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390839/