简体   繁体   English

使用正则表达式对HTML5输入类型编号进行动态验证的问题

[英]Problem with HTML5 input type number dynamic validation with regex

I have a dynamic input generated with a simple jQuery(...).apend(...) that draw this code on my webpage: 我有一个通过简单的jQuery(...).apend(...)生成的动态输入,该输入在我的网页上绘制了以下代码:

<input type="number" name="19000003" min="0" max="99999999" required="" step="0.1"
oninput="/^(?:\d{0,8})(?:,\d{0,3})?$/.test(this.value) ? this.value : this.value = this.value.slice(0,-1);">

I can validate the first part (maximum size of characters including ','), but it gives me an error when y try to validate decimals. 我可以验证第一部分(包括“,”在内的字符的最大大小),但是当y尝试验证小数时,它给我一个错误。

he specified value "111." 他将值指定为“ 111”。 is not a valid number. 不是有效数字。 The value must match to the following regular expression: -?(\\d+|\\d+.\\d+|.\\d+)([eE][-+]?\\d+)? 该值必须与以下正则表达式匹配:-?(\\ d + | \\ d +。\\ d + |。\\ d +)([eE] [-+]?\\ d +)?

When I test the regex code on the Chrome console it works (like these examples) 当我在Chrome控制台上测试正则表达式代码时,它可以正常工作(就像这些示例一样)

/^(?:\d{0,8})(?:,\d{0,3})?$/.test('1234,12');
/^(?:\d{0,8})(?:,\d{0,3})?$/.test('123,');

but doesn't works inside the input. 但在输入内部不起作用。 What could I be doing wrong? 我可能做错了什么?

Your regexp does not work because you are trying to match a , on the input. 因为你想匹配您的正则表达式不工作,在输入。 However, even if you see a , on the browser, internally It is stored as . 但是,即使你看到了,在浏览器上,它内部存储为. (probably to avoid the sort of problems you are facing now when the browser uses different locales) (可能是为了避免浏览器使用其他语言环境时您现在面临的问题)

So use /^\\d{1,8}(?:\\.\\d{1,3})?$/ for your regex instead. 因此,将/^\\d{1,8}(?:\\.\\d{1,3})?$/用作您的正则表达式。

Here I leave a demo of the code. 在这里,我留下了代码的演示。 I have added an alert for every keypress so you can see how It is stored. 我为每个按键都添加了一个alert ,以便您查看其存储方式。 Try to write 1,1 and see what happens. 尝试写1,1 ,看看会发生什么。

 <input type="number" name="19000003" min="0" max="99999999" required="" step="0.1" oninput="alert(this.value); /^\\d{1,8}(?:\\.\\d{1,3})?$/.test(this.value) ? this.value : this.value = this.value.slice(0,-1);"> 

In addition to Julio's answer 除了朱利奥的答案

note that step="0.1" can also break your form validation. 请注意, step="0.1"也可能破坏您的表单验证。

It's better to adhere to your regex validation (for 3 decimals, step="0.001" ) 最好坚持进行正则表达式验证(对于3个小数, step="0.001"

More info here 更多信息在这里

try to separate function from element 尝试将功能与元素分开

  const myElement = document.getElementById("someInput"); myElement.oninput = function(ev) { /^(?:\\d{0,8})(?:,\\d{0,3})?$/.test(this.value) ? this.value : this.value = this.value.slice(0, -1); } 
  <input type="number" id="someInput" name="19000003" min="0" max="99999999" required="" step="0.1" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM