如何使用jquery验证插件检查至少两个单词? [英] How to check at least two words with jquery validation plugin?

查看:85
本文介绍了如何使用jquery验证插件检查至少两个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个:

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

完美无缺,但如果我在第一个字符之前有空格或两个空格之间有空格,不工作。

Works perfectly, but if i have a space before the first character or two space between the words, its not working.

有什么想法吗?
谢谢

Any idea? Thanks

推荐答案

单词之间有两个空格:

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

参见 .test RegExp

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

\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.");

这篇关于如何使用jquery验证插件检查至少两个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆