Angel Politis
Angel Politis

Reputation: 11313

How to check an array of forbidden words?

I am trying to make the label red if a user enters a forbidden word on keyup. I can do this with one word, but no matter what I've tried I've failed badly when it comes to multiple.

This is my code:

username.onkeyup = function() {

    var forbiddenWords = ["ffff, aaaa, bbbb, hhhh, ggggg"];
    var username_value = this.value.split('');

    function isForbiddenWord(value) {
        for (var i = 0; i < forbiddenWords.length; i++) {
            var rgx = new RegExp(forbiddenWords[i], 'gi');
            if (rgx.test(value)) {
                return true;   
            }
            else {
                return false;
            }
        }
    }

    if (isForbiddenWord(this.value) == true) {
        console.log('Username contains swearing word. Please, remove it');
        document.getElementById('username_label').style.color = "red";
    }
    else {
        if (username_value[username_value.length - 1] === "-" || username_value[username_value.length - 1] === "_") {
            console.log('Username cannot end in dash (-) or underscore (_)');
            this.value = this.value.slice(0, -1);
        }
        else if (this.value.length < 4) {
            console.log('Username cannot be less than 4 characters');
            document.getElementById('username_label').style.color = "red";
        }
        else {
            document.getElementById('username_label').style.color = "green";
        }
    }
}

Upvotes: 0

Views: 442

Answers (2)

charlietfl
charlietfl

Reputation: 171690

Try only returning false only after the loop is completed, not for each iterationas else. That way if any are true the return true will break the loop, otherwise when loop is done all will be determined to be false.

Right now as soon as the first false is encountered the function is returning false and will ignore any subsequent words in array

function isForbiddenWord(value) {
    for (var i = 0; i < forbiddenWords.length; i++) {
        var rgx = new RegExp(forbiddenWords[i], 'gi');
        if (rgx.test(value)) {
            return true;   
        }
        // move this outside loop
        //else {
           // return false;
        //}
    }
    return false;
}

And as noted in other answer fix quotes in array

Upvotes: 3

M4tini
M4tini

Reputation: 446

Your array of forbidden words currently consists of 1 word: "ffff, aaaa, bbbb, hhhh, ggggg". Your code works if you use this as the array:

var forbiddenWords = ["ffff", "aaaa", "bbbb", "hhhh", "ggggg"];

Upvotes: 2

Related Questions