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 specia
If you really want to check for all those special characters, it's easier to use a regular expression:
var str = $('#Search').val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('Your search string contains illegal characters.');
}
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 the alert
.
var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-="
var check = function(string){
for(i = 0; i < specialChars.length;i++){
if(string.indexOf(specialChars[i]) > -1){
return true
}
}
return false;
}
if(check($('#Search').val()) == false){
// Code that needs to execute when none of the above is in the string
}else{
alert('Your search string contains illegal characters.');
}
You are checking whether the string contains all illegal characters. Change the ||
s to &&
s.
You could also use the whitelist method -
var str = $('#Search').val();
var regex = /[^\w\s]/gi;
if(regex.test(str) == true) {
alert('Your search string contains illegal characters.');
}
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.