Banned words but not if with more words

坚强是说给别人听的谎言 提交于 2020-01-07 09:43:54

问题


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:


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.



来源:https://stackoverflow.com/questions/25974314/banned-words-but-not-if-with-more-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!