Skip to content Skip to sidebar Skip to footer

Javascript Regular Expression (page Range Validation)

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've created such

Solution 1:

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*,?)+$");

Solution 2:

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

Solution 3:

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

Solution 4:

^((\\d+(\\-\\d+)?, ?)*(\\d+(\\-\\d+)?))+$

Post a Comment for "Javascript Regular Expression (page Range Validation)"