简体   繁体   English

正则表达式允许空字符串

[英]Regex allow empty string

I'm trying to apply a regex in which a number can be formatted to two decimal places, I've been able to achieve this.我正在尝试应用一个正则表达式,其中可以将数字格式化为两位小数,我已经能够实现这一点。 But I am unable to delete the first character in the string because my test will fail if there is no match.但是我无法删除字符串中的第一个字符,因为如果没有匹配项,我的测试将失败。 How can I modify this regex to support the deletion of the entire value?如何修改此正则表达式以支持删除整个值?

/^[0-9]+(\\.([0-9]{1,2})?)?$/

https://codesandbox.io/s/k2qlq0w68r https://codesandbox.io/s/k2qlq0w68r

For the specific thing that you're doing (input validation), you can probably just eschew your regex altogether and just use <input type="number"> with a step : 对于具体的事情你做的(输入验证),你可能只需要避开干脆您正则表达式,只是使用<input type="number">step

<input type="number" step="0.01">

You can check the validity property to check if anything is incorrect. 您可以检查validity属性来检查是否有任何不正确的地方。 I believe something like document.getElementById("id").checkValidity() will give you what you want. 我相信诸如document.getElementById("id").checkValidity()会为您提供所需的东西。

See also: Validating forms using JavaScript and Form Validation Part 2: The Constraint Validation API (JavaScript) . 另请参阅: 使用JavaScript表单验证来验证表单第2部分:约束验证API(JavaScript)


If you still wish to use the regex, it's probably easier to separate the only-decimal and part non-decimal cases: 如果仍然希望使用正则表达式,则将仅十进制和部分非十进制的情况分开可能会更容易:

/^(?:\d+(?:\.\d{0,2})?|\.\d{1,2})$/

This matches the following numbers: 100 , 12.5 , 10. , 8.51 , .67 , .0 此相匹配的以下数字: 10012.510.8.51.67.0

But rejects the following: .032 , . 但拒绝如下: .032. , [empty string] ,[空字符串]

I would recommend that you run the validation after the user types in the number, not as they are currently typing it in. Otherwise, it will be impossible for them to type .01 , as your regex will reject them when pressing . 我建议您在用户键入数字运行验证,而不是像他们当前正在键入的那样。否则,他们将无法输入.01 ,因为您的正则表达式将在按下时拒绝它们. .

You can you this regex if you want to make decimal before dot optional 如果要在点之前设置小数点,则可以使用此正则表达式

^([0-9])?(?(1)(.([0-9]{1,2})?)?|(.[0-9]{1,2}))$

Is this what you want? 这是你想要的吗?

If you want a regex that also accepts the empty string: 如果要一个正则表达式也接受空字符串:

/^([0-9]+(\\.([0-9]{1,2})?)?|)$/

But I would suggest to you to not assume that the input is valid while the user puts it into your input but instead validate the value after the user is done editing (eg by using a loose focus event). 但是我建议您不要在用户将其输入到您的输入中时假设输入是有效的,而是在用户完成编辑后(例如,通过使用松散焦点事件)验证该值。

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

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