Reputation: 512
I need regex that validated the comma separated numbers with min and max number limit. i tried this regex but no luck
^(45|[1-9][0-5]?)$
i want the list like this one (min number is 1 and max number is 45)
23,45,3,7,1,9,34
Upvotes: 1
Views: 1055
Reputation: 23472
I would be tempted to use a combination of regex (depending on need) and array iterators (not for..in
enumeration) (ES5 in example)
var reIsPattern = /^[+\-]?(?:0|[1-9]\d*)$/;
function areNumsInRange(commaString, min, max) {
return commaString.split(',')
.map(Function.prototype.call, String.prototype.trim)
.every(function(item) {
return reIsPattern.test(item) && item >= min && item <= max
});
}
var s = '23,45,3,7,1,9,34';
document.body.textContent = areNumsInRange(s, 1, 45);
Or perhaps just simply
function areNumsInRange(commaString, min, max) {
return commaString.split(',').every(function(item) {
var num = Number(item);
return num >= min && num <= max;
});
}
var s = '23,45,3,7,1,9,34';
document.body.textContent = areNumsInRange(s, 1, 45);
Upvotes: 0
Reputation: 89547
It isn't a job for regex (regex are not handy with numbers, imagine the same with a more complicated range like (247,69352) that needs to build a giant pattern). So my advice is to split your string and then to check your items one by one.
A way without regex:
function numsInRange(s, min, max) {
var items = s.split(',');
for (var i in items) {
var num = parseInt(items[i], 10);
if (num != items[i] || num < min || num > max)
return false;
}
return true;
}
var s='23,45,3,7,1,9,34';
console.log(numsInRange(s, 1, 45)); // true
console.log(numsInRange(s, 1, 44)); // false
Upvotes: 2
Reputation: 435
This regex will do the job:
\b(([1-3][0-9])|(4[0-5])|[1-9])\b
Upvotes: 1