1

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
Javid
  • 482
  • 1
  • 6
  • 26
  • 1
    http://stackoverflow.com/questions/7944065/regex-for-javascript-validation-of-comma-separated-numbers or http://stackoverflow.com/questions/16620980/comma-separated-numbers-regex or http://stackoverflow.com/questions/17960858/regex-javascript-numbers-comma-separated – Xotic750 Nov 04 '15 at 15:10

3 Answers3

2

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

demo

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
1

This regex will do the job:

\b(([1-3][0-9])|(4[0-5])|[1-9])\b
Conrado Costa
  • 434
  • 2
  • 12
0

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);
Xotic750
  • 22,914
  • 8
  • 57
  • 79