Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

188
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda