Javascript 如何使用jquery验证插件检查至少两个单词?
所以我有这个:Javascript 如何使用jquery验证插件检查至少两个单词?,javascript,jquery,jquery-validate,Javascript,Jquery,Jquery Validate,所以我有这个: jQuery.validator.addMethod("tagcheck", function(value, element) { var space = value.split(' '); return value.indexOf(" ") > 0 && space[1] != ''; }, "At least two words."); 很完美,但是如果我在第一个字符前有一个空格,或者在单词之间有两个空格,它就不起作用了 有什么想法吗? 谢
jQuery.validator.addMethod("tagcheck", function(value, element) {
var space = value.split(' ');
return value.indexOf(" ") > 0 && space[1] != '';
}, "At least two words.");
很完美,但是如果我在第一个字符前有一个空格,或者在单词之间有两个空格,它就不起作用了
有什么想法吗?
谢谢在单词之间有两个空格:
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
见和
\w
匹配任何字母字符<代码>\s匹配任何空格字符
让我们将其合并到您的代码片段中:
var tagCheckRE = new RegExp("(\\w+)(\\s+)(\\w+)");
jQuery.validator.addMethod("tagcheck", function(value, element) {
return tagCheckRE.test(value);
}, "At least two words.");
谢谢:jQuery.validator.addMethod(“tagcheck”,函数(值,元素){return value.match(\\w+)(\\s+)(\\w+);},“至少两个字。”);