Only integers:
/^\d+$/ # explanation \d match a digit + one or more times
Numbers with no more than two decimal places:
/^\d+(?:\.\d{1,2})?$/ # explanation \d match a digit... + one or more times ( begin group... ?: but do not capture anything \. match literal dot \d match a digit... {1,2} one or two times ) end group ? make the entire group optional
Notes:
- Slashes indicate the beginning and end of a pattern.
^ and $ are the beginning and end of string anchors. Without them, he will look for matches anywhere on the line. So /\d+/ matches '398501' , but also matches 'abc123' . Anchors ensure that the entire string matches the given pattern.- If you want to allow negative numbers, add
-? before the first \d . Again ? means "zero or once."
Usage example:
var rx = new RegExp(/^\d+(?:\.\d{1,2})?$/); console.log(rx.test('abc')); // false console.log(rx.test('309')); // true console.log(rx.test('30.9')); // true console.log(rx.test('30.85')); // true console.log(rx.test('30.8573')); // false
source share