问题
I have a field that you enter your name in and submit it. I would like the receive peoples first and last names and to do this i need to check if the value contains at least 2 words. This is what I am using right now but it doesn't seem to work.
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;
}
}
回答1:
str.trim().indexOf(' ') != -1 //there is at least one space, excluding leading and training spaces
回答2:
You could use the String.Split() method:
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;
}
}
If you were to pass "John Doe" as the name value, values would equal {"john", "doe"}
http://www.w3schools.com/jsref/jsref_split.asp
Edit: Added filter to remove empty values. Source: remove an empty string from array of strings - JQuery
回答3:
The easy solution (not 100% reliable, since "foo " returns 4, as @cookiemonster mentioned):
var str = "Big Brother";
if (str.split(" ").length > 1) {
// at least 2 strings
}
The better solution:
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
}
回答4:
Probably not the best solution overall (see the other answers), but one that shows how to count the number of times a regexp matches a string:
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:
Change this line from your snippet
var matches = NAME.match(/\b[^\d\s]+\b/g);
to this
var matches = NAME.match(/\S+/g);
or to this, if numbers should be excluded
var matches = NAME.match(/\b([a-z]+)\b/gi);
Side (funny) note: Your snippet works just fine. Check the jsBin
回答6:
I would just check for whitespace by running a for loop.
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;
}
If the name doesn't have a space, knowing that there is a space between the first and last name, it would alert("You entered an invalid name");
来源:https://stackoverflow.com/questions/25344603/javascript-check-if-value-has-at-least-2-or-more-words