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");
nhahtdh
56.9k15 gold badges131 silver badges164 bronze badges
asked Oct 31, 2013 at 20:07
user2855405
5152 gold badges7 silver badges20 bronze badges
2 Answers 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.
answered Oct 31, 2013 at 20:14
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
prompt CONTAINS three or more words, seperated by spaces, only alphabetical characters.
You can try this regex:
/^[a-z]+( +[a-z]+){2,}$/i
answered Oct 31, 2013 at 20:13
anubhava
791k67 gold badges604 silver badges671 bronze badges
lang-js
\wwill match digits also. Besides that your expression will require, for a string three character long, to have an additional space.