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");
2
  • @Floris- \w will match digits also. Besides that your expression will require, for a string three character long, to have an additional space. Commented Oct 31, 2013 at 20:22
  • @edi_allen - you were right. Don't know what I was thinking. Commented Oct 31, 2013 at 20:49

2 Answers 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

You can try this regex:

/^[a-z]+( +[a-z]+){2,}$/i

2 Comments

^/ should probably be /^, isn't it?
@Boaz: Thanks so much, it was a typo, fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.