2011-01-30 85 views
2

所以我有这样的:如何用jquery验证插件检查至少两个单词?

jQuery.validator.addMethod("tagcheck", function(value, element) { 
    var space = value.split(' '); 
    return value.indexOf(" ") > 0 && space[1] != ''; 
}, "At least two words."); 

作品完美,但如果我有字与字之间的第一个字符之间有一个空格或两个空间,它不工作。

有什么想法? 感谢

回答

4

它有句话之间两个空格:

var string = "one two"; 
var space = string.split(" "); // ["one", "", "two"] There is a space between the first 
// space and second space and thats null. 

它的第一个字符之前,一个空格。

var string = " foo bar"; 
var location = value.indexOf(" "); // returns 0 since the first space is at location 0 

你想要的是使用正则表达式。

var reg = new RegExp("(\\w+)(\\s+)(\\w+)"); 
reg.test("foo bar"); // returns true 
reg.test("foo bar"); // returns true 
reg.test(" foo bar"); // returns true 

.testRegExp

\w匹配任何字母字符。 \s匹配任何空格字符。

让我们将此主题融入您的代码段为您提供:

var tagCheckRE = new RegExp("(\\w+)(\\s+)(\\w+)"); 

jQuery.validator.addMethod("tagcheck", function(value, element) { 
    return tagCheckRE.test(value); 
}, "At least two words."); 
+0

感谢:jQuery.validator.addMethod( “tagcheck” 功能(价值元素){ 回报value.match(“(\\ w + )(\\ s +)(\\ w +)“); },”至少两个单词“。 – passatgt 2011-01-30 14:45:25

相关问题