0

My email validation is not checking condition properly when i give without name only domain name in text box example @gmail.com it shows valid like valid email i need to raise alert this situation. but it works at checks domain name it works fine.

My code:

if(!(email.endsWith("@yahoo.com") || email.endsWith("@gmail.com"))){ alert("Email Should be in @yahoo.com or @gmail.com"); $("#txtEmail").val(''); document.getElementById("txtEmail").focus(); return false; } 

Thank you

6
  • you can always add another check of startsWith if you are not thinking of regex which is pretty good solution Commented May 15, 2017 at 13:37
  • Use regex to validate email Commented May 15, 2017 at 13:39
  • From what you posted the JS is doing what it's supposed to. I'd suggest using a regex to check the if the entered values are valid mail addresses and when that's the case you could check for yahoo/gmail. (btw: don't even try to write an email-regex, save yourself the trouble and google for a good one ) Commented May 15, 2017 at 13:39
  • 2
    Possible duplicate of Using a regular expression to validate an email address Commented May 15, 2017 at 13:39
  • Correct me if I'm wrong but I think regex is not a good solution, because he want to check if the email is from yahoo.com or gmail.com. Commented May 15, 2017 at 13:43

2 Answers 2

1

Add email.lastIndexOf("@") === 0 to your condition, like this:

if(email.lastIndexOf("@") === 0 || !(email.endsWith("@yahoo.com") || email.endsWith("@gmail.com"))){ 
Sign up to request clarification or add additional context in comments.

Comments

0

Try with this kind of regexp

if (email.match(/^\S+@(yahoo|gmail)+\.com$/g)) 

This will check that you have content before the @ and validate that is it yahoo or gmail.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.