wizard
wizard

Reputation: 103

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.

Upvotes: 0

Views: 78

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

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.

Upvotes: 3

Sean T
Sean T

Reputation: 2504

If you're using html5 controls use step, min and max.

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

Upvotes: 3

Related Questions