【问题标题】:How to allow only 2 digits and 1 digit after the comma (.)?如何在逗号 (.) 后只允许 2 位数字和 1 位数字?
【发布时间】:2021-03-04 23:20:19
【问题描述】:

我的问题是我无法将正确的RegExp 放在一起。 我的目标是在逗号前最多允许 3 位数字,并且仅当有小数时,逗号后才允许 1 位数字。对于这种行为,我必须使用哪个 RegExp 或正则表达式?

想要的允许结果:000.0、00.0、0.0、000、00、0

这是当前的代码,但问题是这里也可以放置 4 位数字而不带小数:

inputFormatters: [
  FilteringTextInputFormatter.allow(RegExp(r'^\d{1,3}\.?\d{0,1}')),
],

我已经浏览了这些,但它们不适合我:

Javascript Regex to allow only 2 digit numbers and 3 digit numbers as comma separated

Javascript regex to match only up to 11 digits, one comma, and 2 digits after it

Jquery allow only float 2 digit before and after dot

Flutter - Regex in TextFormField

Allow only two decimal number in flutter input?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:
    RegExp(r'^\d{0,3}(\.\d{1})?$')
    

    试试这个正则表达式

    我也认为用逗号表示您的平均小数 (.) 并考虑到您想要小数点前 3 位和小数点后 1 位

    TextFormField(
      autoValidateMode: AutoValidateMode.always,
      validator: (value) {
        return RegExp(r'^\d{0,3}(\.\d{1})?$').hasMatch(value) ? null : 'Invalid value';
      },
    )
    

    【讨论】:

    • 不幸的是在飞镖中不起作用,是的,我的意思是小数,我编辑了我的问题
    • 是的,你必须使用验证器,让我编辑答案
    • @Nuqo 我已经添加了如何在 dart 中使用 RegEx 的示例看看
    • 如果它对您有用,您也可以将其标记为已接受?
    【解决方案2】:

    输入格式化程序不是这种情况,因为它格式化数据可视化并且您想要的格式相互包含。您应该将TextFormFieldvalidator 属性与@Andrej 的验证器一起使用,或者使用RegExp

    TextFormField(
      autoValidateMode: AutoValidateMode.always,
      validator: (value) {
        return RegEx(r'^\d{1,3}(\.\d)?$').hasMatch(value) ? null : 'Invalid value';
      },
    )
    

    RegExp 正在工作 here

    【讨论】:

      【解决方案3】:

      我不是正则表达式专家,所以我只能建议你使用这个辅助函数:

        bool match(String input) {
          if (input.split('.').length == 1) {
            // if there is no dot in the string
            // returns true if the length is < 4
            return (input.length < 4) ? true : false;
          } else if (input.split('.').length > 1){
            // if there is more than one dot in the string
            return false;
          } else {
            // if there is a dot in the string
            // returns true if there are < 4 digits before the dot and exactly 1 digit 
            // after the dot
            return (input.split('.')[0].length < 4 && input.split('.')[1].length == 1)
                ? true
                : false;
          }
        }
      

      【讨论】:

      • 如何在扩展 'TextInputFormatter' 的自定义类中使用它或作为 inputFormatter?
      • 就像 BambinoUA 在他的回答中使用验证器一样。 PS我稍微编辑了代码。
      • 谢谢,我最终使用了与我的第一个“FilteringTextInputFormatter”一起使用的解决方案。
      • 没问题,很高兴能帮到你。如果您对此有任何疑问,可以问我。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      相关资源
      最近更新 更多