Home > OS >  Using regex to validate input data with potentially repeated pattern
Using regex to validate input data with potentially repeated pattern

Time:09-11

I'm trying to use Regex to validate the form field data in javascript. The accepted patterns are for a single item, Org-1234 or for multiple, Org-1234, Org-56789. For multiple items, they have to be separated by comma (with potential space around it). The matching should be case insensitive.

I came up with this regex: /^(org-\d )([ ,](org-\d ))*/i, however it only matches the first capture group. How could I make it work with an optional repeated pattern, i.e., if there is more character outside of the first match group, it has to conform with the same pattern, separated by comma?

CodePudding user response:

Another idea may be to split the string an test the resulting trimmed and lowercased items for starting with org and having one or morge numbers at the end. Something like:

const value1 = `Org-1234, Org-56789`;
const value2 = `Org-1234, Org-`;
const value3 = `Org-1234`;
const value4 = `NOPE-1234`;
const value5 = `Org-1, Org-2`;

const validate = t => 
  t.startsWith(`org`) && /\d $/.test(t);
const isValid = term => {
  const _t = term.split(`,`)
    .map(v => v.trim().toLowerCase());
  return _t.length === _t.filter(validate).length;
};

console.log(isValid(value1));
console.log(isValid(value2));
console.log(isValid(value3));
console.log(isValid(value4));
console.log(isValid(value5));

CodePudding user response:

Try the following (?<=^|,\s)(org-\d (?=(?:,\s|$))) Check here https://regex101.com/r/tdB9If/1

  • Related