开发者

How to check at least two words with jquery validation plugin?

So i have this:

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

Works p开发者_运维技巧erfectly, but if i have a space before the first character or two space between the words, its not working.

Any idea? Thanks


It has two spaces between the 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.

It has a space before the first character.

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

What you want is to use a regular expression.

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

See .test and RegExp.

\w matches any alphabetic character. \s matches any space character.

Let's incorporate that into your code snippet for you:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜