I would like to validate the user input field to only allow user to input +1,-1,+10,-10 and +25,-25, nothing else. What is the regular expression for this restriction?
Try with:
/^[-+](1|10|25)$/
It will allow one of your 6 possibilities.
I wouldn't bother with a regexp. Presumably, you're going to ultimately need to parse the number from a String to an int, yes? In which case you could just immediately parse it and check the outcome is as expected, although this won't enforce the "+" sign if that's mandatory - but manually checking for the sign before parsing would be simple.
If you're absolutely allowing only the specified inputs, and nothing else, then the following regex will do it:
/^[-+](1|10|25)$/
But what if someone enters "10" -- ie "+10", but without the plus sign? Is that allowed or not? You haven't specified. If it is, then the +/- needs to be optional, so the regex changes to this:
/^[-+]?(1|10|25)$/
Note that this regex also has start and end anchors (ie ^
and $
), meaning that it won't allow any other characters in the string. Without them, it could match a string that contained "+20" in amongst other text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With