Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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

like image 533
Filip Spiridonov Avatar asked Dec 17 '10 06:12

Filip Spiridonov


People also ask

How to use RegEx to Validate?

To validate a field with a Regex pattern, click the Must match pattern check box. Next, add the expression you want to validate against. Then add the message your users will see if the validation fails. You can save time for your users by including formatting instructions or examples in the question description.

What is ?: In RegEx?

It indicates that the subpattern is a non-capture subpattern. That means whatever is matched in (?:\w+\s) , even though it's enclosed by () it won't appear in the list of matches, only (\w+) will.

What is RegEx 0 9?

The RegExp [0-9] Expression in JavaScript is used to search any digit which is between the brackets. The character inside the brackets can be a single digit or a span of digits.

How to check 0 9 JavaScript?

Use the [^0-9] expression to find any character that is NOT a digit.


2 Answers

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*,?)+$");
like image 67
cdhowie Avatar answered Oct 13 '22 00:10

cdhowie


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

like image 22
codaddict Avatar answered Oct 13 '22 00:10

codaddict