Angel Politis Angel Politis - 6 months ago 16
HTML Question

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";
}
}
}

Answer

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"];
Comments