Reputation: 83
I'm struggling to find a way to allow numeric only numbers that can also be negative, but also allow only one leading zero.
Goal Examples: 0, 12345, -555
Bad Examples: -0, 01235, -012
I have the following so far, but cant seem to work in the negative character properly. If I type - first nothing can be typed afterwards, but it should allow 1-9: /^([-0]|[1-9]\d*)$/
Tried this as well, but no luck: /^[-]?(0|[1-9]\d*)$/
Any help would be greatly appreciated.
----updated code---- //can type in a 0, but not a hypen for negative. If I rotate the ?:0|-? to be ?:-|0? I can then type in the hypen, but not a zero.
function(evt) {
evt = (evt) ? evt : window.event;
let expect = evt.target.value.toString().trim() + evt.key.toString();
if (!/^(?:0|-?[1-9][0-9]*)$/.test(expect)) {
evt.preventDefault();
} else {
return true;
}
Upvotes: 0
Views: 58
Reputation: 5375
Try the following: (see here)
\b0\b|-?\b(?!^0)[1-9]+[0-9]*\b
Upvotes: 1
Reputation: 336158
Let's keep it simple:
/^(?:0|-?[1-9][0-9]*)$/
Explanation:
^ # Start of string
(?: # Start of non-capturing group
0 # Match either a zero (and nothing else)
| # or
-? # an optional -
[1-9] # a digit between 1 and 9
[0-9]* # 0 or more further digits
) # End of group
$ # End of string
Upvotes: 1