1

I am completely new to JS, and having trouble figuring out how to validate that theinputvia promptCONTAINS 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's user avatar
nhahtdh
56.9k15 gold badges131 silver badges164 bronze badges
askedOct 31, 2013 at 20:07
user2855405's user avatar
2
  • @Floris-\w will match digits also. Besides that your expression will require, for a string three character long, to have an additional space.CommentedOct 31, 2013 at 20:22
  • @edi_allen - you were right. Don't know what I was thinking.CommentedOct 31, 2013 at 20:49

2 Answers2

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

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

answeredOct 31, 2013 at 20:14
Barmar's user avatar
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
answeredOct 31, 2013 at 20:13
anubhava's user avatar

2 Comments

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

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.