0

Trying to validate my form and set up a variable for invalid characters, but I'm having trouble getting them recognized because they're just a bunch of symbols? -

function validation(){
        var Name =
        document.getElementById("name").value;
        var Email = document.getElementByID("email").value;
        var invalidSymbol = /[\~\`\!\#\$\%\^\&\*\(\)\-\+\{\}\:\\\;\"\'\<\>\?\,\]/;

        if Name == ""{
            alert("Please enter your name");
            document.getElementById("Name").focus();
            return false;
        }else if (Email == "" | | Email.indexOf("@")<1 || Email.lastIndexOf("@")+2 || Email.lastIndexOf(".")+2>=Email.indexOf("@").length || Email.match(invalidSymbol)){
            alert ("Please enter a valid e-mail address");
            document.getElementById("email").focus();
            return false;
        }else{
            return true;
        }
}
gyre
  • 16,369
  • 3
  • 37
  • 47
maria
  • 41
  • 4

1 Answers1

1
var desired = stringToReplace.replace(/[^\w\s]/gi, '')

As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.

The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).

As stated here: javascript regexp remove all special characters by annakata

Community
  • 1
  • 1
Josh
  • 718
  • 10
  • 25