Javascript: Check if string contains only letters, numbers, whitespace, and specific symbols

Viewed 760

I want to do a string validation, the rule is the string only allowed to have the following characters:

  • Letters
  • Numbers
  • Space or Whitespace
  • Specific symbols : ( ) . - /

If the string contains a character that is not in the above list, it should return a false result

I tried to do it like this:

return value.match(/[().-\/]/) || value.match("^[A-Za-z0-9]+$") || (value.indexOf(' ') !== -1) ? true : false;

It works if you have only disallowed character, if I have allowed characters mixed in it will return true

1 Answers
// test if string contains something that is not: A-Z, a-z, 0-9, whitespaces and symbols :)./(-
const conditionRegex = /([^a-zA-Z0-9:\.\/\(\)\-\s])/g;
return conditionRegex.test(anotherString);

Not sure if you want to check if contains or not any different character, but you just need to invert if that is the case. The example I wrote will return true if something different is typed.

PS: to invert just remove the ^ at the start like this: /([a-zA-Z0-9:\.\/\(\)\-\s])/g

Related