Yesterday I\'ve got a task to implement a validation on the field where user can enter the range of pages that he wants to download.
After reading some tutorials, I
^((\\d+(\\-\\d+)?, ?)*(\\d+(\\-\\d+)?))+$
You can try the regex:
^(\d+(-\d+)?)(,\d+(-\d+)?)*$
To allow white spaces between you can do:
^(\s*\d+\s*(-\s*\d+\s*)?)(,\s*\d+\s*(-\s*\d+\s*)?)*$
Rubular link
You need to escape the backslashes in the string, or JavaScript will strip them out or interpret them as escape sequences:
var patt1 = new RegExp("^(\\s*\\d+\\s*\\-\\s*\\d+\\s*,?|\\s*\\d+\\s*,?)+$");
You can define patt1
without new RegExp
, using a regular expression literal
. Otherwise you'll have to escape all '\' in the regular expression string (using '\\').
var patt1 = /^(\s*\d+\s*\-\s*\d+\s*,?|\s*\d+\s*,?)+$/g;
now patt1.test("1, 2, 3-5, 6, 8, 10-12")
should evaluate to true
, patt1.test("1, 2, 3-5, 6, 8, 10-12,nocando")
to false