Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda