简体   繁体   English

HTML5输入模式属性 - 正则表达式失败

[英]HTML5 input pattern attribute - regex fails

I'm a bit stumped trying to get the following regex to work 我试图让以下正则表达式工作有点难过

<!DOCTYPE html>
<html>
<body>

<form action="/....php">
  Amount: <input type="text" name="amount" pattern="^\$(\d{1,3}(\,\d{3})*|(\d+))(^\.\d{2})?$" title="Please enter as $XXX,XXX no decimal">
  <input type="submit">
</form>



</body>
</html>

I tried dropping the leading carrot and trailing dollar too, as I know these are implied, but it still won't validate the the number entered is of the form $XXX,XXX with no decimal. 我尝试丢弃领先的胡萝卜和尾随美元,因为我知道这些是隐含的,但它仍然不会验证输入的数字是$ XXX,XXX没有小数的形式。 Other regex parsers are working fine and validate the regex should work: https://regex101.com/r/BZKMK4/1 其他正则表达式解析器工作正常并验证正则表达式应该工作: https//regex101.com/r/BZKMK4/1
Are there published limitations to the input regex you can use in the pattern attribute? 您是否可以在模式属性中使用输入正则表达式的已发布限制?

A simplified regex seems to do the trick: \\$\\d{1,3}(,\\d{1,3})* 简化的正则表达式似乎可以解决这个问题: \\$\\d{1,3}(,\\d{1,3})*

No need to specifically negate decimals with the (^\\.\\d{2})? 不需要用(^\\.\\d{2})?专门否定小数(^\\.\\d{2})? - just not including anything here will make the field invalid if a decimal is typed since no dots are allowed in the first place. - 如果输入小数,只是不包括任何内容会使该字段无效,因为首先不允许使用点。 I think this is what was messing with it since JS regexes do not support this feature, and your link specified a PHP style regex, not JS 我认为这是搞乱它的,因为JS正则表达式不支持这个功能,你的链接指定了PHP风格的正则表达式,而不是JS

 input:invalid { border: 2px solid red; } 
 <label for="input-amount">Amount</label> <input type="text" id="input-amount" pattern="\\$\\d{1,3}(,\\d{1,3})*" placeholder="$XXX,XXX"> 

Also, a small suggestion from the UI-side of things, there's no need to make people type the $ sign, just put that outside of the input next to it so that it's implied and all people have to worry about are the numbers. 此外,从UI方面的一个小建议,没有必要让人们输入$符号,只需将它放在旁边的输入旁边,这样就暗示了所有人不必担心的是数字。

Right now you type $ alone and it's an invalid field, which is not a great experience. 现在你单独输入$并且它是一个无效的字段,这不是一个很好的体验。 here's my suggested change: 这是我建议的改变:

 .prefix, input { border: 2px solid #CCC; font-size: 14px; padding: 1px; } .prefix { display: inline-block; border-right-width: 0; } input { border-left-width: 0; } input:invalid { border-color: red; } 
 <label for="input-amount">Amount</label> <span class="prefix">$</span><input type="text" id="input-amount" pattern="\\d{1,3}(,\\d{1,3})*" placeholder="XXX,XXX"> 

It's not perfect, but you get the idea. 它并不完美,但你明白了。

Thanks. 谢谢。 That got me where I need to be. 这让我成为了我需要的地方。 Here's my final regex: 这是我最后的正则表达式:

   ^\$[1-9]\d{0,2}((,\d{3})*|\d*)$

Support with or without comma, ie $10,000 is valid, and so is $10000 支持带或不带逗号,即10,000美元有效,10000美元也是如此

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

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