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
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.
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.
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.
Use the [^0-9] expression to find any character that is NOT a digit.
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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With