Home > Blockchain >  Is there a regex pattern for custom page range validation in javascript and react
Is there a regex pattern for custom page range validation in javascript and react

Time:09-16

I need a pattern that

Matches:

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

Not Matches:

  • 1,,,,

  • 1, 4-5-

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

I have tried a pattern but it doesn't work:-

  1. /^(\d-\d,?|\d*,?)*$/g

and

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

React code for allowing input in the particular pattern

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

I have referred many links but in StackOverflow but doesn't match Can anyone give a solution that matches the above pattern

Please try here https://jsfiddle.net/mayankshukla5031/4zqwq1fj/ If the pattern match let me know

CodePudding user response:

One possible regex:

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

See https://regex101.com/r/txVh3e/1 for test cases or the following JavaScript demo:

const regex = /^(\d (-\d )?, )*\d (-\d )?$/;
const patterns = [
  '1',
  '1, 4-5',
  '1, 4-5, 8, 11, 13-14',
  '1,,,,',
  ', 4-5-',
  ', 4--------2233-----,,,,',
  '1, 2, 3, 4, 5',
];
for (const pattern of patterns) {
  if (pattern.match(regex)) {
    console.log(`'${pattern}' is valid`);
  } else {
    console.log(`'${pattern}' is invalid`);
  }
}

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.

CodePudding user response:

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

  • Related