Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

javascript - Banned words but not if with more words

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...