Javascript Not Matching correct words for validation
This is a follow up to another post I put here
So I have a form and I dont want to accept certain words. However Say you Enter "Post" I dont want it to match "pos" so I have accomplished that part the script no longer matches parts just whole words but for some reason if I enter "Positive" it does not match "positive" with the word boundaries on the regex
var resword = new Array("positive","pos","negative","neg","neutral", "neu","twitter","itunes","facebook","android","forums","RSS Feeds");
var valueLen = $("#aname").val().length;
var fail=false;
var filterElem = $('#aname');
var filterName = $('#aname').val();
$.each(resword,function(){
if ( filterName.toLowerCase().match("\b"+this+"\b")) {
filterElem.css('border','2px solid red');
window.alert("You can not开发者_如何学Go include '" + this + "' in your Filter Name");
fail = true;
}
});
I would suggest a bit cleaner way to implement this that takes all the words and puts them in one regular expression. This method also has a feature enhancement to do just one alert that shows all the illegal words. Here's the code which you can see working in this jsFiddle.
function check() {
var resword = new Array("positive","pos","negative","neg","neutral", "neu","twitter","itunes","facebook","android","forums","RSS Feeds");
// build one regex with all the words in it
// assumes that the words themselves dont' have regex characgers in them
var regex = new RegExp("\\b" + resword.join("\\b|\\b") + "\\b", "ig");
var filterElem = $('#aname');
var match, plural, errors = [];
// call regex.exec until no more matches
while ((match = regex.exec(filterElem.val())) != null) {
errors.push(match[0]); // accumulate each illegal word match
}
// if there were any errors, put them together and prompt the user
if (errors.length > 0) {
plural = errors.length > 1 ? "s" : "";
filterElem.css('border','2px solid red');
alert("You can not include the word" + plural + " '" + errors.join("' and '") + "' in your Filter Name");
}
return(errors.length == 0); // return true if no errors, false if errors
}
You need to double escape your backslashes (\
) since it's in a string:
.match("\\b"+this+"\\b")
精彩评论