Reputation: 7375
I have checked the below link for regular expression
Regex to match 2 digits, optional decimal, two digits
regular expression should accept whole number or decimal points. max length should be 10 numbers before decimal and 4 digits after decimal.
tried this below code from above link (2 digit decimal point)
\d{0,2}(\.\d{1,2})?
var patt =new RegExp("\d{0,2}(\.\d{1,2})?")
undefined
patt.test(1)
true
patt.test(1.1)
true
patt.test(11)
true
patt.test(111.111)
true
for 3 digits after decimal also it is giving true value, which is invalid.
Upvotes: 0
Views: 13830
Reputation: 15616
Why don't you just check:
input < Math.pow(10,10) && input % Math.pow(10,-4) == 0
Upvotes: 0
Reputation: 12452
You have to use delimiters, to determine where your match starts and where it ends. And you say max length should be 10 numbers before decimal and 4 digits after decimal
so your limits are incorrect too:
var patt = /^\d{1,10}(\.\d{1,4})?$/;
var patt = new RegExp(/^\d{1,10}(\.\d{1,4})?$/);
console.log( patt.test(1) ); // true
console.log( patt.test(1.1) ); // true
console.log( patt.test(11.11) ); // true
console.log( patt.test(111.111) ); // true
console.log( patt.test(1111.1111) ); // true
console.log( patt.test(1111111111.1111) ); // true
console.log( patt.test(111.11111) ); // false, because to long after decimal
console.log( patt.test(11111111111.1111) ); // false, because to long before decimal
Or as suggested here, not using RegExp
and instead use a literal. There could be support issues with RegExp
in some browsers. The output is the same, so better use this solution:
var patt = /^\d{1,10}(\.\d{1,4})?$/;
console.log( patt.test(1) ); // true
console.log( patt.test(1.1) ); // true
console.log( patt.test(11.11) ); // true
console.log( patt.test(111.111) ); // true
console.log( patt.test(1111.1111) ); // true
console.log( patt.test(1111111111.1111) ); // true
console.log( patt.test(111.11111) ); // false, because to long after decimal
console.log( patt.test(11111111111.1111) ); // false, because to long before decimal
Upvotes: 9
Reputation: 39
here is the code that is working for me
function IsValidNumericCode(number,messageDiv,msg){
var reNumeric = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
var result = reNumeric.test(number); if(!result){ messageDiv.html(msg);
messageDiv.fadeIn(400).fadeOut(400).fadeIn(400).fadeOut(400).fadeIn(400);
}else{ messageDiv.html('');} return result;
Upvotes: -1
Reputation: 2297
The regex doesn't say the string should end with the last character, or start with the first one. Try:
var patt = /^\d{1,2}(\.\d{1,2})?$/;
For your 10 digits before and 4 digits after requirement:
var patt = /^\d{1,10}(\.\d{1,4})?$/;
Upvotes: 2