Adam Adam - 1 year ago 112
Javascript Question

Validate input value against blacklist array

I'm currently using jQuery Validation, I have a form with four input fields - Word, Country, Age & Sex.

Country, Age & Sex validate without any problems, but Word doesn't want to validate - I'm trying to get the Word value to check its self against a blacklist before validating, I'm trying to prevent users submitting offensive words.

At the moment, whatever word I type into the Word input field, it always shows as an error and doesn't want to validate.

If anyone can see where I'm going wrong, I'd appreciate the help!



/* Blacklist Array */
var blacklist = ['foo', 'bar', 'fizz', 'buzz', /* many more banned words... */ ];

/* Blacklist Validation */
jQuery.validator.addMethod("word", function(value) {
var in_array = $.inArray(value, blacklist);
if (in_array == -1) {
return false;
} else {
return true;

/* Submit Validation */
errorPlacement: function(error, element){},
rules: {
word: {
required: true
country: {
required: true
age: {
required: true
sex: {
required: true
submitHandler: function(form) {


<form methord="post" name="wordsubmit" id="submit">
<div class="inner">
<input class="word" name="word" placeholder="Your Word" type="text"/>
<select class="country" name="country" size='1'>
<option value="">Your country</option>
<select class="age" name="age" size='1'>
<option value="">Age</option>
<option value="18-24">18-24</option>
<option value="25-34">25-34</option>
<option value="35+">35+</option>
<select class="sex" name="sex" size='1'>
<option value="">Sex</option>
<option value="Male">Male</option>
<option vlaue="Female">Female</option>
<input class="submit" name="submit" type="submit" value="Submit"/>

Answer Source

The logic in the word method you add is backwards; if the word entered is not found in the array (ie. $.inArray returns -1) then you want to return true as this word is valid.

That being the case, you can simplify the logic to just this:

/* Blacklist Validation */
jQuery.validator.addMethod("word", function(value) {
    return $.inArray(value, blacklist) == -1;

Working example

Note in the example I have removed the error message suppression so you can see the code working.

It would also be worth making sure that the case is consistent for values in the blacklist array, so you can then cast the entered word to the same case using value.toUpperCase() or value.toLowerCase(), as currently FoO won't match foo and will be marked as valid.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download