Reputation: 3144
I want to validate numbers in an input in Javascript.
The input should accept:
I have used this regex:
^(-?)[\d]*$
It works well, but it also accepts only the minus character alone '-' . I want to exclude this possibility. I could of course replace *
with +
, but that would exclude the empty string.
How can I do it so that a -
must be followed by at least one number, but a completely empty string is still OK?
Upvotes: 7
Views: 8737
Reputation: 39
The below regex should fulfill your requirements:
^(|-?\d+)$
Here is a demo
Let's dissect the regex to understand how it works
^()$
: ^
denotes the start of the string and $
signifies the end. ()
tells the matcher to capture everything enclosed. So in our case, it means that our input should be an exact match.|
is a boolean OR i.e. returns positive if either of the regexes is satisfied.-?\d+
matches the positive and negative numbers as follows
-?
matches -
between zero and one times\d+
matches a digit between one to unlimited times|
OR operator. That is the null or the empty input check.With all these combined, we arrive at the required regex.
Upvotes: 3
Reputation: 626738
You may make the digits obligatory and enclose the whole number matching part with an optional group:
/^(?:-?\d+)?$/
See the regex demo
Details
^
- start of the string(?:-?\d+)?
- an optional non-capturing group matching 1 or 0 occurrences of:
-?
- an optional -
\d+
- 1 or more digits$
- end of string.Upvotes: 7