1

I am completely new to JS, and having trouble figuring out how to validate that the input via prompt CONTAINS three or more words, seperated by spaces, only alphabetical characters.

This is what I have:

var p = prompt("Enter a phrase:", "");
var phr = p.search(/^[^0-9][2,3]$/);

  if(phr != 0)
{
   alert("invalid");return
}
else{document.write("phr");
4

2 回答 2

2

Use:

if (/^([a-z]+\s+){2,}[a-z]+$/i.test(p))

Explanation:

  • [a-z] = alphabetic character
  • [a-z]+ = 1 or more alphabetic character, i.e. a word
  • [a-z]+\s+ = word followed by 1 or more whitespace characters
  • ([a-z]+\s+) = at least 2 words with whitespace after each
  • ([a-z]+\s+){2,}[a-z]+ = the above followed by 1 more word
  • ^([a-z]+\s+){2,}[a-z]+$ = anchor the above to the beginning and end of the string

The i modifier makes it case-insensitive, so it will allow uppercase letters as well.

于 2013-10-31T20:14:35.177 回答
1

prompt CONTAINS three or more words, seperated by spaces, only alphabetical characters.

You can try this regex:

/^[a-z]+( +[a-z]+){2,}$/i
于 2013-10-31T20:13:09.767 回答