Banned words but not if with more words

2019-09-24 12:09发布

I find solution, to ban some words if they are entered in input field. The problem is that i need ban them only when somebody use them as single word, not when are entered with more words.

Example:

If %bannedword% was entered then ERROR must show up, but if somebody write

" %bannedword% wordnotbanned "

all must be marked as correct input fill, without any ERROR.

What i must do to everything works fine?

Here is the jQuery

$('#submit').click(function() {

var bannedWords = ["black", "white"],
regex = new RegExp('\\b' + bannedWords.join("\\b|\\b") + '\\b', 'i');
var zalvalid = !regex.test($('#zalmie').val().toLowerCase());

if(!zalvalid) {

    $('#zwynik').addClass("hover").html('<strong>ERROR:</strong>');
    $('#zalmie').focus();
    return false;

} else {

    $('#zwynik').addClass("hover").html('<strong>NICE ONE!</strong>');

}

});

and here is the Fiddle: http://jsfiddle.net/p16954wc/

1条回答
走好不送
2楼-- · 2019-09-24 12:14

I have changed the bannedwords array, that will be used for regExp. You must also include the scenario to handle witespaces. So I have added thoes in bannedWords array.

$('#submit').click(function() {

    var bannedWords = ["black ", "white ", "black", "white"],
    regex = new RegExp('\\b' + bannedWords.join("\\b|\\b") + '\\b', 'i');
    var zalvalid = !regex.test($('#zalmie').val().toLowerCase());

if(!zalvalid) {
    $('#zwynik').addClass("hover").html('<strong>ERROR:</strong>');
    $('#zalmie').focus();
    return false;
    } else {
    $('#zwynik').addClass("hover").html('<strong>NICE ONE!</strong>');
    }

});

Here's a link to fiddle!

Earlier, you were not able to handle the scenario where: Example : black something. So, You must have regExp which must be able to validate "black " and "white " .

If your list of banned word is long , then just add extra space after each word.

You can also automate you banWord array creation.

查看更多
登录 后发表回答