javascript检查值是否至少包含2个或更多单词

时间:2014-08-16 22:32:46

标签: javascript regex string input

我有一个字段,您输入您的名字并提交。我想接收人的名字和姓氏,为此我需要检查该值是否包含至少2个单词。这就是我现在正在使用的东西,但它似乎不起作用。

function validateNameNumber(name) {
    var NAME = name.value;
    var matches = NAME.match(/\b[^\d\s]+\b/g);
    if (matches && matches.length >= 2) {
        //two or more words
        return true;
    } else {
        //not enough words
        return false;
    }
}

6 个答案:

答案 0 :(得分:4)

str.trim().indexOf(' ') != -1 //there is at least one space, excluding leading and training spaces

答案 1 :(得分:1)

您可以使用String.Split()方法:

function validateNameNumber(name) {
    var NAME = name.value;
    var values = name.split(' ').filter(function(v){return v!==''});
    if (values.length > 1) {
        //two or more words
        return true;
    } else {
        //not enough words
        return false;
    }
}

如果你要通过" John Doe"作为名称值,值将等于{" john"," doe"}

http://www.w3schools.com/jsref/jsref_split.asp

修改:添加过滤器以删除空值。资料来源:remove an empty string from array of strings - JQuery

答案 2 :(得分:0)

简单的解决方案(不是100%可靠,因为“foo”返回4,正如@cookiemonster所提到的):

var str = "Big Brother";
if (str.split(" ").length > 1) {
    // at least 2 strings
}

更好的解决方案:

var str = "Big Brother";
var regexp = /[a-zA-Z]+\s+[a-zA-Z]+/g;
if (regexp.test(str)) {
    // at least 2 words consisting of letters
}

答案 3 :(得分:0)

从您的代码段中更改此行

var matches = NAME.match(/\b[^\d\s]+\b/g);

到这个

var matches = NAME.match(/\S+/g);

或者,如果要排除数字

var matches = NAME.match(/\b([a-z]+)\b/gi);

侧面(有趣)注意:您的代码段工作得很好。查看jsBin

答案 4 :(得分:0)

可能不是总体上最好的解决方案(参见其他答案),但是显示了如何计算正则表达式匹配字符串的次数:

function validateNameNumber(name) {
    var nameValue = name.value;
    var regexp = /\b[^\d\s]+\b/g;
    var count = 0;
    while (regexp.exec(nameValue)) ++count;
    if (count >= 2) {
        //two or more words
        return true;
    } else {
        //not enough words
        return false;
    }
}

答案 5 :(得分:0)

我只是通过运行for循环来检查空格。

var correctFormat = false;
for (var i = 0; i = i < name.length; i++) {
    if (name[i] === " ") {
       correctFormat = true;
    }
}
if (correctFormat === false) {
    alert("You entered an invalid name");
    return false;
} else {
    return true;
}

如果名称没有空格,知道名字和姓氏之间有空格,那就alert("You entered an invalid name");