I have tried below regular expression to validate the number with following criteria
/^\d{3,10}(\.\d{2})?$/
a, number should be minimum 3 , maximum 10 (including .) digits and it may contain . and two decimal point
Examples
valid numbers
123
1234
12345
123456
1234567
12345678
123456789
1234567890
123.00
1234.02
12345.03
123456.04
1234567.05
Invalid numbers
1
12
1.11
1.1111
12345678.12
But my regex fail in case of 1234567890.00
CodePudding user response:
You can use:
^(?![.\d]{11,}$)\d{3,10}(?:\.\d\d)?$
Explanation
^
Start of string(?![.\d]{11}$)
Negative lookahead, assert not 11 or more digits or dots till the end of the string\d{3,10}
Match 3-10 digits(?:\.\d\d)?
Optionally match.
and 2 digits$
End of string
See a regex demo.
CodePudding user response:
I see a contradiction in your description of 3 to 10 digits including .
, and your invalid example 1.11
, which has 3 chars (digits and .
)
Here is a regex with tests assuming you want to test for 3 to 10 chars (digits and .
) :
const input = [
'123',
'1234',
'12345',
'123456',
'1234567',
'12345678',
'123456789',
'1234567890',
'1.23',
'123.00',
'1234.02',
'12345.03',
'123456.04',
'1234567.05',
'1',
'12',
'1.1111',
'1.22.33',
'12345678.12',
'1234567890.00'
];
const regex = /^(?=.{3,10}$)\d (\.\d{2})?$/;
input.forEach(str => {
let valid = regex.test(str);
console.log(str ' => ' valid);
});
Output:
123 => true
1234 => true
12345 => true
123456 => true
1234567 => true
12345678 => true
123456789 => true
1234567890 => true
1.23 => true
123.00 => true
1234.02 => true
12345.03 => true
123456.04 => true
1234567.05 => true
1 => false
12 => false
1.1111 => false
1.22.33 => false
12345678.12 => false
1234567890.00 => false
Explanation of regex:
^
-- start of string(?=.{3,10}$)
-- positive lookahead asserting 3 to 10 chars\d
-- 1 chars(\.\d{2})?
-- optional.nn
pattern$
-- end of string