Reputation: 394
I have the following regular expression which performs very basic validation to allow only integers and should not allow any floating point numbers and negative numbers. I found the below expression as one of the ways to do so:
var reg = new RegExp('^(([0-9]+)|\.[0-9]+)$');
This expression correctly validates the following inputs:
validatePercentage(56.67); --> not an integer
validatePercentage(67); --> integer
validatePercentage(-5667); --> should not be negative
However, I'm unable to understand the usage of '\.' in the expression (that somehow seems to be making a difference to the output). Can somebody please explain how exactly is the regex working to eliminate negative inputs? Thanks in advance.
Upvotes: 1
Views: 93
Reputation: 943240
.
in a regex means "any character"\.
in a regex means "a period character"\.
in a JavaScript string literal means .
.This code is an attempt at using 2, but because the regex is being constructed using a string (almost always a mistake) it ends up being a 3 which gets converted into a 1.
The regex appears to be an attempt at "Zero or a positive integer or a positive float that is less than one" but is mangled by the string phase to be "Zero or a positive integer either of which may be preceded by any character at all".
The correct regex would probably be something more like:
var reg = /^[1-9][0-9]+(?:\.0+)?$/
If you really want a test for a positive integer then you'd probably be better off with:
value == parseInt(value, 10) && value > 0
(or > -1 if you want to allow 0 as a value).
Upvotes: 9
Reputation: 89557
To figure a literal dot in a pattern, the dot must be escaped, otherwise the dot may match any characters except newlines.
When you use the object notation with a javascript string to define a pattern, backslashes must be escaped that gives:
var reg = new RegExp('^(([0-9]+)|\\.[0-9]+)$');
or
var reg = /^(([0-9]+)|\.[0-9]+)$/;
You can write too:
var reg = new RegExp(/^(([0-9]+)|\.[0-9]+)$/);
Upvotes: 3