0

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.

5
  • 9
    This is not a job for a regex. Commented Aug 9, 2019 at 15:05
  • 2
    if you only need those specific numbers you could put a start and end char to the regex ^(12|24|36|48|60|72|84|96|108|120)$, but in general I think @Pointy is right. Commented Aug 9, 2019 at 15:07
  • function isValid (input){ return (input % 12 === 0) && (input>11) && (input<121); } function doingStuffWithInput(input) { if (isValid(input)){ //do stuff } else{ alert("error, not valid"); } If you wish to do it without regex Commented Aug 9, 2019 at 15:13
  • This page about anchors might be helpful rexegg.com/regex-anchors.html Commented Aug 9, 2019 at 15:16
  • @Onheiron thanks it worked Commented Aug 9, 2019 at 15:34

2 Answers 2

3

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

<input type="number" step="12" min="0" max="120" name="multiplesOfTwelve"/> 
Sign up to request clarification or add additional context in comments.

7 Comments

Probably also min=0 or min=12
You'd still need server-side validation ( and that should not be regex-based ) to filter for fabricated POST requests.
@collapsar They've not specified what server side framework they're using so it's hard for me to state that :)
@collapsar - Well, that's a truism, not really a specific to Sean's answer. :-) No client-side validation is sufficient on its own.
@T.J.Crowder You are right. The Q however only asks for (regex-based) validation in general which would include client- and server-side, while this answer is limited to the client.
|
3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.