简体   繁体   English

正则表达式仅允许特定数字

[英]Regex to allow only particular numbers

I have a field which should only take values divisible of 12. Such as 12,24,36,48,60,72,84,96,108,120. 我有一个字段,该字段只能取整为12的值,例如12,24,36,48,60,72,84,96,108,120. I used below regex : 我在正则表达式下面使用了:

12|24|36|48|60|72|84|96|108|120

But this also allows values such as 12abc, 12-!& . 但这还允许使用诸如12abc, 12-!& It's allowing alphabets or special characters with the numbers. 它允许带有数字的字母或特殊字符。 Is there any regex to only allow 12,24,36,48,60,72,84,96,108,120 as input. 是否有任何正则表达式只允许输入12,24,36,48,60,72,84,96,108,120作为输入。

I agree with Pointy that this doesn't sound like a job for regex. 我同意Pointy的观点,这听起来并不是正则表达式的工作。 If you're using HTML5 input validation, definitely go for the approach Sean T shows . 如果您使用的是HTML5输入验证,则一定要使用Sean T展示的方法

But from what you've said it's matching, it's just that you don't have start-of-input ( ^ ) and end-of-input anchors ( $ ): 但是从您所说的是匹配的角度来看,只是您没有输入开始锚( ^ )和输入结束锚( $ ):

^(?:12|24|36|48|60|72|84|96|108|120)$

(You need the non-capturing group or the anchors become part of the alternative they're next to.) (您需要非捕获组,否则锚点将成为其旁边替代项的一部分。)

If you want to allow harmless spaces: 如果要允许无害空间:

^\s*(?:12|24|36|48|60|72|84|96|108|120)\s*$

Obviously in either case (doing something like this or Sean's HTML5 approach), if this is being sent to a server, you need to validate it on the server as well. 显然,无论哪种情况(执行类似操作或使用Sean的HTML5方法),如果将其发送到服务器,则也需要在服务器上对其进行验证。

如果您使用的是html5控件,请使用stepminmax

<input type="number" step="12" min="0" max="120" name="multiplesOfTwelve"/>

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

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