颤振:验证Radix 10数字

时间:2018-05-13 18:49:13

标签: validation flutter

我正在iPhone上测试数字验证。 这是我的代码片段:

child: new TextFormField(

  controller:  sales,
  keyboardType: TextInputType.numberWithOptions(decimal: true),
  decoration: const InputDecoration(
      filled: true,
      fillColor: CupertinoColors.white,
      border: const OutlineInputBorder(),
      labelText: ‘Sale amount’,
      suffixText: ‘ZAR’,
      suffixStyle:
      const TextStyle(color: Colors.green)),
  maxLines: 1,
  validator: (val) {
    if (val.isEmpty ) return 'Amount is required';
    if (val.contains(",")) {
      sales.text = val.replaceAll(new RegExp(r","), ".");
    }
    if (sales.text.indexOf(".") != sales.lastIndexOf(".")) {
      return 'Enter valid amount.';
    }
    else
    return null;
  },
),

现在,我正在用这个数字25,52,85测试验证 - 这显然不是一个有效的数字,但它可能是iPhone的数字软键盘上允许的。 (另外有趣的是,在美国iPhone上,我们在数字软键盘上有逗号而不是fullstop,如果必须存储一个double,则必须将逗号转换为fulstops,我在代码中的validate方法中完成了以上)

enter image description here

现在,当我单击“完成”以验证表单时,错误会导致日志,并且它告诉我它是无效的Radix 10号码。换句话说,Flutter告诉我一个double不能存在,其中有两个逗号/ fullstops。

所以为了解决这个问题,我在这段代码中写了一下,验证这个数字是否包含2个以上的完整停止:

if (sales.text.indexOf(".") != sales.lastIndexOf(".")) {
  return 'Enter valid amount.';
}

但是,我发现这很麻烦,并且想知道是否有办法更优雅地测试它?如何轻松验证数字是否有效?#/ p>

1 个答案:

答案 0 :(得分:1)

.parse是你的家伙。如果需要小数,请选择double.parse,如果不想,请选择int.parse

选中此other StackOverFlow answer并举例说明

相关问题