2014-08-29 123 views
0

jquery中的文本验证字符串包含精确的子字符串不是部分。 例如:输入字符串:的Hello World子字符串:你好有像str.indexof(SubString) >-1 or /SubString/.test(str)验证如果有人在输入文本框中输入他也验证了上述条件,它应该确认确切字符串“你好”不为He。这个怎么做。您的建议将不胜感激。jquery验证字符串包含确切的子字符串

/Hello/.test(Hello世界) - 正确的验证作为你好世界

/Hello/.test(He ..) - 它不应该进行验证,如果它证明了 LLO在 ..

setValidation: function(){ 
$.validator.addMethod("no_Hello_word", function(value) { 
       return /hello/.test(value) || /HELLO/.test(value); 
      }, "Text mustn't contain word hello/HELLO"); 
} 
+0

使用单词边界.. – 2014-08-29 03:37:08

回答

0
$.validator.addMethod("helloworld_word", function(value,element) { 
       return /^((?!helloworld).)*$/i.test(value); 
}, "No Hello world"); 
1

尝试

return !/hello/i.test(value) || /Hello/.test(value)

0

你为什么不这样做?如果用户将在此不能用来验证“他”

var string= "hello, world"; 
var string_array= string.toLowerCase().split(" "); 

if (string_array.indexOf("hello") >= 0){ 
    return true; 
} else { 
    return false; 
} 
+0

既不检查精确的word.instead你好,如果你把他和检查的indexOf它将返回相同的索引即它只是检查索引匹配的字母。 – Anil 2014-08-29 04:10:15

+0

我更改了代码。这对你有用吗? – SivaDotRender 2014-08-29 04:28:41

0

什么这个问题:用空格分割字符串,然后数组中的词搜索:

var exactSearch = function(word, string){ 
    var words = string.split(" "); 

    for(i = 0; i < words.length; i++){ 
     if(word == words[i]){ 
      return true; 
     } 
    } 
    return false; 
} 

见工作实例here

UPDATE

我想我写答案编辑面前的问题。

也许对你有用:

$.validator.addMethod("no_Hello_word", function(value, element) { 
    return (value.toLowerCase && (value.toLowerCase() === "hello")); 
}, 
    "Text mustn't contain word hello/HELLO!" 
); 
0

试试这个:

function isValid(str){ 
    return !/[hH]ello/.test(str); 
} 

// isValid('Hello') -> false 
// isValid('Hello World') -> false 
// isValid('He') -> true 

,如果你想验证是圆的另一种方式,您可以翻转此。

相关问题