I know this question is asked more often here on Stack, but I can't seem to get a straight answer out of the questions already posted.
I need to check if all special characters (except -) are in a string, if so, then give the user an alert.
What I have so far is this:
if($('#Search').val().indexOf('@') == -1 || $('#Search').val().indexOf('#') == -1 || $('#Search').val().indexOf('$') == -1 || $('#Search').val().indexOf('%') == -1 || $('#Search').val().indexOf('^') == -1 || $('#Search').val().indexOf('&') == -1 || $('#Search').val().indexOf('*') == -1 || $('#Search').val().indexOf('(') == -1 || $('#Search').val().indexOf(')') == -1 || $('#Search').val().indexOf('_') == -1 || $('#Search').val().indexOf('\'') == -1 || $('#Search').val().indexOf('\"') == -1 || $('#Search').val().indexOf('\\') == -1 || $('#Search').val().indexOf('|') == -1 || $('#Search').val().indexOf('?') == -1 || $('#Search').val().indexOf('/') == -1 || $('#Search').val().indexOf(':') == -1 || $('#Search').val().indexOf(';') == -1 || $('#Search').val().indexOf('!') == -1 || $('#Search').val().indexOf('~') == -1 || $('#Search').val().indexOf('`') == -1 || $('#Search').val().indexOf(',') == -1 || $('#Search').val().indexOf('.') == -1 || $('#Search').val().indexOf('<') == -1 || $('#Search').val().indexOf('>') == -1 || $('#Search').val().indexOf('{') == -1 || $('#Search').val().indexOf('}') == -1 || $('#Search').val().indexOf('[') == -1 || $('#Search').val().indexOf(']') == -1 || $('#Search').val().indexOf('+') == -1 || $('#Search').val().indexOf('=') == -1)
{
// Code that needs to execute when none of the above is in the string
}
else
{
alert('Your search string contains illegal characters.');
}
But this doesn't seem to work... Can anyone help me on this matter?
Thanks in advance!
Guido
You are checking whether the string contains all illegal characters. Change the
||
s to&&
s.You could also use the whitelist method -
The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.
If you really want to check for all those special characters, it's easier to use a regular expression:
The above will only allow strings consisting entirely of characters on the ranges
a-z
,A-Z
,0-9
, plus the hyphen an space characters. A string containing any other character will cause thealert
.