Search code examples
javascriptjqueryinputcpu-wordrestrict

jquery block words from list if used as single word, not when with others


I must try one more time in here with this problem. As I could notice, resolve my problem is not so simple. I have input text field in which some words from specified list can't be used, but only when the each word from list is entered as single, not with other words.

So i define 'var'

var bannedWords = ["black", "white", "red", "blue"],

Now when somebody enter any word from list above, should see error message. But more important is the case when he enter any word from list above with any other and then this must be accepted.

In short, when somebody enter:


"black" - ERROR,

"this is black" - ACCEPTED,

"white is cool" - ACCEPTED,

"this is red color" - ACCEPTED


Very important is that i need to be able simply add any each other word to this list, so everything still could act.

I try to find help in here, but i think no one understand me, or was not able to help. Is anyone who can give me a tip?


Solution

  • Could be optimized .. but: http://jsfiddle.net/1819tb2m/

    var badWords = ["black", "white", "red", "blue"];
    
    $("input").keyup(function(){
        for(var i = 0; i < badWords.length; i++)
        {
            if(this.value == badWords[i])
            {
                $("p").text("BAD WORD!");
                return;
            }        
        }
        $("p").text("accepted " + this.value);
    })