javascript验证可以防止某些单词

时间:2015-01-28 19:47:58

标签: javascript validation

我试图阻止用户将某些字词和特殊字符输入到"和","或"," /"等文本字段中, " \&#34 ;.如何将变量设置为两个或更多条件,或者我应该如何更好地处理此变量。

首先,我试图阻止用户进入"和#34;或者在文本字段中。

function watchForWords(text) {
  if (!text) {
  return true;
  }
  var isValid = (text.value != "and" || text.value != "or");
  if (!isValid) {
  text.style.backgroundColor = "#ff8";
  }
return isValid;
}

2 个答案:

答案 0 :(得分:3)

您有几个选项,具体取决于您要如何定义"字。"如果您指的是一串文本,您可以使用简单的内容,例如indexOf来检查一个字符串是否包含另一个字符串。如果你的字面意思是单词,在空格分隔的意义上,你可能想要一个正则表达式。

简单:



var blacklist = ["and", "or", "/", "\\"];

function validate(input) {
  for (var i = 0; i < blacklist.length; ++i) {
    if (input.indexOf(blacklist[i]) >= -1) {
      // String is present
      return false;
    }
  }
  // No blacklisted strings are present
  return true;
}

console.log("this is a clean string", validate("this is a clean string")); // true
console.log("and this is a dirty string", validate("and this is a dirty string")); // false
console.log("andthis is also dirty", validate("andthis is also dirty")); // false
&#13;
&#13;
&#13;

正则表达式:

&#13;
&#13;
var blacklist = ["and", "or", "/", "\\"];

function validate(input) {
  for (var i = 0; i < blacklist.length; ++i) {
    var expr = new RegExp("\\b" + blacklist[i] + "\\b");

    if (expr.exec(input)) {
      // String is present
      return false;
    }
  }
  // No blacklisted strings are present
  return true;
}

console.log("this is a clean string", validate("this is a clean string")); // true
console.log("and this is a dirty string", validate("and this is a dirty string")); // false
console.log("andthis is also dirty", validate("andthis is also dirty")); // true, note the difference from the previous because of no word sep
&#13;
&#13;
&#13;

答案 1 :(得分:2)

var isValid = !/(\w+)?and|or|\/|\\\w+/.exec(myString)

如果isValid不包含“and”或“or”或您声明的任何其他字符,则为真,如果它包含至少其中一个字符,则为false