Regex to allow numbers only between 1 and 20000

Although I’m doubtful this is the most-efficient solution, this should do the trick.

/^((1[0-9]{0,4})|([1-9][0-9]{0,3})|20000)$/

Be warned that this is string-matching, not type-casting, so things like decimal places and zero-filling will not be matched.

Regex Explained:

graph

Unit test I used:

for (var i = 0; i < 100000; i++) {
	var should = i > 0 && i <= 20000;
	if (should !== /^((1[0-9]{0,4})|([1-9][0-9]{0,3})|20000)$/.test('' + i)) {
		console.log('FAILED:', i);
	}
}
console.log('DONE');

Browse More Popular Posts

Leave a Comment