Flutter 中正则表达式验证中的小数或带符号数值

san*_*jay 2 regex dart flutter

我正在尝试使用正则表达式验证来检查 Flutter 应用程序中的小数值或带符号的数值。

有效的输入就像

  • 12.3
  • -12.33

我曾经WhitelistingTextInputFormatter限制用户输入。请参考下面的代码:

TextFormField(
    key: AppKeys.emailField,
    keyboardType: TextInputType.emailAddress,
    controller: controller.emailTextController,
    inputFormatters: [
      WhitelistingTextInputFormatter(RegExp(r'[0-9-]\d*(\.\d+)?')),
    ],
    maxLength: 100,
    decoration: InputDecoration(
      labelText: Strings.emailPrompt,
      counterText: '',
      prefixIcon: Icon(Icons.email),
    ),
    //validator: Validator.validateEmail,
    onSaved: (String val) {
      //_email = val;
    },
  );
Run Code Online (Sandbox Code Playgroud)

但这似乎并没有起作用。尽管它仅适用于数字,但它不接受点字符。正则表达式还应该接受位于开头的一个减号字符和位于中间的一个点字符。

非常感谢任何帮助。提前致谢。

小智 7

这会工作得很好。如果输入无效字符,文本字段不会变为空白。

WhitelistingTextInputFormatter(RegExp(r'(^\-?\d*\.?\d*)')),
Run Code Online (Sandbox Code Playgroud)