Validation 颤振:验证浮动

Validation 颤振:验证浮动,validation,flutter,Validation,Flutter,我试图让dart验证我的用户将在我的表单中输入的浮动。我从这个关于浮点数正则表达式(例如12.830)的SO线程()中获得了指导,并在我的flatter应用程序中进行了尝试 new TextFormField( controller: amt_invested, keyboardType: TextInputType.number, inputForm

我试图让dart验证我的用户将在我的表单中输入的浮动。我从这个关于浮点数正则表达式(例如12.830)的SO线程()中获得了指导,并在我的flatter应用程序中进行了尝试

new TextFormField(
                        controller:  amt_invested,
                        keyboardType: TextInputType.number,
                        inputFormatters: [WhitelistingTextInputFormatter(new RegExp(r'[+-]?([0-9]*[.])?[0-9]+'))],
                        decoration: const InputDecoration(
                            filled: true,
                            fillColor: CupertinoColors.white,
                            border: const OutlineInputBorder(),
                            labelText: 'Amount invested',
                            prefixText: '\R',
                            suffixText: 'ZAR',
                            suffixStyle:
                            const TextStyle(color: Colors.green)),
                        maxLines: 1,
                        validator: (val) => val.isEmpty ? 'Amount is required' : null,
                      ),
然而,正则表达式阻止我在浮动中进入句号,这与所谓的线程所说的相反。我如何让它正常工作


如果要匹配
123,请在部分中向下滚动几行。

在这里,您确实希望匹配
123。
,因为它是通往
123.45
的踏脚石

因此,将RegExp更改为
newregexp(r'^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$)
当您使用数字键盘时,您可能可以省去前导的
^
和尾随的
$

这个例子

main() {
  RegExp re;

  re = new RegExp(r'[+-]?([0-9]*[.])?[0-9]+');
  print(test(re, '1234'));
  print(test(re, '1234.'));
  print(test(re, '1234.5'));
  print(test(re, '1234a'));
  print(test(re, '1234..'));

  print('---');

  re = new RegExp(r'^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$');
  print(test(re, '1234'));
  print(test(re, '1234.'));
  print(test(re, '1234.5'));
  print(test(re, '1234a'));
  print(test(re, '1234..'));
  print(test(re, '1234 '));
}
输出

true
false <- this causes your problem
true
false
false
---
true
true
true
false
false
false
true
假的