【问题标题】:Knockout Js Regex no negative numbers淘汰赛 Js 正则表达式没有负数
【发布时间】:2018-01-01 03:22:01
【问题描述】:

我正在尝试找到一个正则表达式代码来禁用用户输入的负数。 我正在玩弄代码,试图找到正确的代码,但没有取得太大的成功。

我当前的代码是:

Price: ko.observable().extend({
        required: true,
        pattern: '^[0-9].$'
    })

【问题讨论】:

  • 那个句号应该是小数吗?小数点后面可以有数字吗?
  • 我不确定你所说的期间是什么意思。它可以是十进制的,只要它的数字为 1 及以上
  • 你可以使用这个有用的正则表达式测试器:regex101.com
  • 试试'^[0-9]+(?:[.][0-9]+)?$'

标签: regex knockout.js


【解决方案1】:

你可以使用数字组\d

pattern: '^\d+\.?$'

这符合以下内容:

  • 数字必须从行首开始
  • 必须包含 1 个或多个数字
  • 可以有字符“.” 0或1次
  • 数字必须在行尾结束

以下是一些匹配示例:“34”、“5”、“45687654”、“1.”、“198289”。

我注意到你说你想避免负数,你的解决方案是将数字压缩到行的开头和结尾。也可以使用负号lookbehind来检查数字是否没有负号,比如with

pattern: '(?<!-)\b\d+\.?'

我还添加了单词边界检查 (\b),这样就不会尝试匹配 -123 中的 23

【讨论】:

    【解决方案2】:

    在这种情况下,为什么需要允许用户在输入字段中输入负数并根据负数验证输入?

    相反,您可以阻止用户输入负数/字符串。

    这使用 JavaScript,但您不必编写自己的验证例程。相反,只需检查 validity.valid 属性。当且仅当输入在该范围内时才会如此。

    解决方案 1:

    <html>
    <body>
    <form action="#">
      <input type="number" name="test" min=0 oninput="validity.valid||(value='');">
    </form>
    </body>
    </html>

    解决方案 2:

    以下解决方案支持验证多个输入。

    // Select your input element.
    var numInput = document.querySelector('input');
    
    // Listen for input event on numInput.
    numInput.addEventListener('input', function(){
        // Let's match only digits.
        var num = this.value.match(/^\d+$/);
        if (num === null) {
            // If we have no match, value will be empty.
            this.value = "";
        }
    }, false)
    &lt;input type="number" min="0" /&gt;

    解决方案 3:

    我还没有测试过以下解决方案,但这也可能会有所帮助......

    '/^\d+$/''^\d+$' 模式都可能对您当前的方法有所帮助。

    Price: ko.observable().extend({
            required: true,
            pattern: '/^\d+$/'
        })
    

    Original Solution and Reference here..

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 2013-05-29
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 2013-08-14
      • 1970-01-01
      相关资源
      最近更新 更多