Filip Spiridonov
Filip Spiridonov

Reputation: 36250

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 pattern which in my opinion should work, but it doesn't :(

Can you give me a hint where is the mistake, or how it should be done in the better way.

<script type="text/javascript">
var patt1=new RegExp("^(\s*\d+\s*\-\s*\d+\s*,?|\s*\d+\s*,?)+$");
document.write(patt1.test("1, 2, 3-5, 6, 8, 10-12"));
</script>

P.S. You can test it here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_regexp_test

More examples:

etc... like in MS Office or Adobe PDF Reader

Upvotes: 5

Views: 3500

Answers (4)

Caner
Caner

Reputation: 59308

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

Upvotes: 1

KooiInc
KooiInc

Reputation: 122986

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

Upvotes: 2

cdhowie
cdhowie

Reputation: 169403

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

Upvotes: 9

codaddict
codaddict

Reputation: 455400

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

Upvotes: 7

Related Questions