-1

Consider the following regex:

^[^-\s][a-zA-Z\sàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ\d!@#$\+%&\'*]{1,20}$

I did try it on https://regexr.com/ using as test Collection '98 and matches.

I then did implement it in Node.js:

const myRegex = '^[^-\s][a-zA-Z\sàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ\d!@#$\+%&\'*]{1,20}$';

const name = 'Collection \'98';

if (!name.match(myRegex))
  console.log('NOK');
else
  console.log('OK');

However, it always prints NOK.

Why doesn't the validation work via app?

Emma
  • 27,428
  • 11
  • 44
  • 69
SubZeno
  • 341
  • 3
  • 15
  • When a regex is passed as a string, backslashes are part of string escape sequences. If a string escape sequence is unknown, the backslash is omitted. Double them, or use regex literal notation. – Wiktor Stribiżew May 12 '19 at 20:36

2 Answers2

1

Enclose your regex between slashes (/) instead of quotation marks " and it'll work:

const myRegex = /^[^-\s][a-zA-Z\sàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ\d!@#$\+%&\'*]{1,20}$/;

const name = 'Collection \'98';

if (!name.match(myRegex))
  console.log('NOK');
else
  console.log('OK');
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
1

I'm not sure about your codes, however it seems to me that your expression is correct and it works.

This snippets shows that it would return a match.

const regex = /[^-\s][a-zA-Z\sàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ\d!@#$\+%&\'*]{1,20}/gm;
const str = `Collection '98`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

You can test/modify your expressions in this link.

enter image description here


It appears that you might have forgotten to add your expression in between two forward slashes, which you can simply fix it using /expression/.

Emma
  • 27,428
  • 11
  • 44
  • 69