40

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?

2
  • 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, 2012 at 12:48
  • See this may be help you stackoverflow.com/questions/10505772/…
    – Hkachhia
    Dec 12, 2012 at 12:53

4 Answers 4

100

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.

7
  • 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, 2012 at 13:30
  • It works, even with the international characters ;) Thanks again! Dec 12, 2012 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. Apr 23, 2014 at 11:34
  • Why don't we write /[^a-zA-Z0-9- ]*$/ instead of /^[a-zA-Z0-9- ]*$/?
    – Alston
    Jan 27, 2015 at 7:55
  • @Stallman The meaning is different. Inside the brackets, the ^ negates the list instead of defining the beginning of the string.
    – bfavaretto
    Jan 27, 2015 at 14:49
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.');
}
0
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.

3
  • 4
    This fails for international characters(chinese, arabic etc).I wouldn't use it. Apr 23, 2014 at 11:31
  • == true? Wouldn't if(regex.test(str)) { [...] } suffice?
    – scniro
    Oct 23, 2015 at 0:48
  • Of course it would @scniro. I just put the entire equation for clarity sake. Oct 23, 2015 at 11:36
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.