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?
An empty regular expression matches everything.
If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() .
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.
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.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