38

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?

starball
  • 20,030
  • 7
  • 43
  • 238
Guido Visser
  • 2,209
  • 5
  • 28
  • 41
  • 2
    You need to use a regular expression here instead of a bazillion separate conditions. And you **definitely** have to say how exactly it "doesn't seem to work". – Jon Dec 12 '12 at 12:48
  • See this may be help you http://stackoverflow.com/questions/10505772/checking-for-any-occurrence-of-special-characters-with-jquery – Hkachhia Dec 12 '12 at 12:53

4 Answers4

98

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.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • Added a short explanation. The downside is that it won't allow international characters like `é` and `ñ`, but if you don't need to allow them I believe it's the way to go. – bfavaretto Dec 12 '12 at 13:30
  • It works, even with the international characters ;) Thanks again! – Guido Visser Dec 12 '12 at 15:14
  • 2
    This fails for international characters (chinese, arabic etc). I wouldn't use it. It doesn't look for special characters like anton's example. – Marvin Saldinger Apr 23 '14 at 11:34
  • Why don't we write `/[^a-zA-Z0-9- ]*$/` instead of `/^[a-zA-Z0-9- ]*$/`? – Alston Jan 27 '15 at 07:55
  • @Stallman The meaning is different. Inside the brackets, the `^` negates the list instead of defining the beginning of the string. – bfavaretto Jan 27 '15 at 14:49
  • @bfavaretto what if characters like ☺■☻♣♦♠☼♫♪↕§ these appears on my copied text and I want to validate this on pasting to a text field – tvshajeer Mar 18 '15 at 06:01
  • It seems this example doesn't invalidate whitespace. To do so, use /^[a-zA-Z0-9-]*$/ – Jihoon Baek Sep 20 '16 at 21:42
23
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.');
}
Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
Anton
  • 32,245
  • 5
  • 44
  • 54
6

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.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
2

You are checking whether the string contains all illegal characters. Change the ||s to &&s.

JJJ
  • 32,902
  • 20
  • 89
  • 102