-2

I may just be being thick here but I don't understand why I am receiving this error. Outside of the function the .test() works fine. But inside, I get the error. Was thinking it was something to do with the scope of the .test() function but am I just missing something blindingly obvious here?

     function cFunctionfirst() {
          firstField = document.getElementById("sname_input_first").value;
          document.getElementById("demo").innerHTML = "first: " + firstField;

          console.log(firstField);
          var regex = "!@#$£%^&*()+=[]\\\';,./{}|\":<>?";

          if(regex.test(firstField)){
               console.log('illegal characters used');
          } else {
               console.log('Character okay');
          };
     };
Junayed
  • 61
  • 6
Kye
  • 1

1 Answers1

3

That's because regex is not a RegExp object, but just a string. It should be declared as such (remember to escape special characters using \):

var regex = /[!@#\$£%\^&\*\(\)\+=\[\]\\\';,\.\/\{\}\|":<>\?]/;

Not only have I escaped some special regex characters, but you will need to wrap the entire selection inside unescaped [ and ] brackets, so that you test against a set of characters.

p/s: These are the set characters that need to be escaped: \ ^ $ * + ? . ( ) | { } [ ]

See proof-of-concept example:

function cFunctionfirst(value) {
  var regex = /[!@#\$£%\^&\*\(\)\+=\[\]\\\';,\.\/\{\}\|":<>\?]/;
  if(regex.test(value)){
    console.log('illegal characters used');
  } else {
    console.log('Character okay');
  };
};

cFunctionfirst('Legal string');
cFunctionfirst('Illegal string @$%');

Alternatively, if you don't want to manually escape the characters, you can either use a utility method to do it, or use an ES6 non-regex approach, which is probably a lot less efficient: checkout the JSPerf test I have made. Simply add the blacklisted characters literally in a string, split it, and then use Array.prototype.some to check if the incoming string contains any of the blacklisted characters:

function cFunctionfirst(value) {
  var blacklist = '!@#$£%^&*()+=[]\\\';,./{}|":<>?'.split('');
  if (blacklist.some(char => value.includes(char))) {
    console.log('illegal characters used');
  } else {
    console.log('Character okay');
  };
};

cFunctionfirst('Legal string');
cFunctionfirst('Illegal string @$%');
Terry
  • 48,492
  • 9
  • 72
  • 91