5

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:

  • 1 match
  • 1-2 match
  • -2 not match
  • 1, 2-3, 4, 5-7 match
  • 1 2, 3 not match
  • 1-2-2 not match

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

1
  • Please provide more examples. Commented Dec 17, 2010 at 6:48

4 Answers 4

9

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*,?)+$");
Sign up to request clarification or add additional context in comments.

2 Comments

Hell, yeah! That's what I was missing! You rule :)
This RegExp matches the 1-2-2 format. Check the @codaddict solution bellow.
7

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

Comments

2

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

1 Comment

Thank you also, now I've got the difference.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.