Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
Is there a regex pattern for custom page range validation in javascript and react

I need a regex for page sequences that

matches:

  • 1
  • 1, 4-5
  • 1, 4-5, 8, 11, 13-14

but doesn't match:

  • 1,,,,
  • 1, 4-5-
  • 1, 4--------2233-----,,,,

I have tried the following patterns but they don't work:

/^(\d*-\d*,?|\d*,?)*$/
/^(\d*-{1}\d*,?|\d*,?)*$/

I also want to validate user input while the user types, so the pattern needs to allow tailing - and , in certain cases. The example React code for allowing input with a particular pattern looks like this:

const customPageInputChange = (e) => {
  if(e.target.value.match(/.../) !== null) {
    setCustomPage(e.target.value)
  }
}

See https://jsfiddle.net/mayankshukla5031/4zqwq1fj/ for a full example with input validation.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

One possible regex:

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

See https://regex101.com/r/txVh3e/1 for test cases.

If you also want to check whether the pages are increasing, a regex is not really suitable, and you should opt for checking the strings programmatically.

If you want to validate user input while the user is typing, you need a regex allowing trailing - and ,. One possible regex:

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

See https://regex101.com/r/rKx6lq/1 for test cases and https://jsfiddle.net/qtb4yd7s/ for a demo.

about 4 years ago · Juan Pablo Isaza Report

0

You might use

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

In Javascript you can use regex.test(str) to return a boolean to see if the pattern matched.

In parts, the pattern matches:

  • ^ Start of string
  • \d+ Match 1+ digits
  • (?:-\d+)? Optionally match - and 1+ digits
  • (?: Non capture group to match as a whole part
    • ,\s* Match a comma and optional whitespace chars
    • \d+(?:-\d+)? The same as previous pattern
  • )* Close the non capture group and optionally repeat to als match a single occurrence
  • $ End of string

See a Regex demo

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!