简体   繁体   中英

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. I used below regex :

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

But this also allows values such as 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.

I agree with Pointy that this doesn't sound like a job for regex. If you're using HTML5 input validation, definitely go for the approach Sean T shows .

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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