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

Antony
  • 37
  • 1
  • 9
  • you can always add another check of `startsWith` if you are not thinking of `regex` which is pretty good solution – Agam Banga May 15 '17 at 13:37
  • Use regex to validate email – Durga May 15 '17 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 ) – garglblarg May 15 '17 at 13:39
  • 2
    Possible duplicate of [Using a regular expression to validate an email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – Durga May 15 '17 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. – schaffioverflow May 15 '17 at 13:43
  • http://stackoverflow.com/questions/46155/validate-email-address-in-javascript http://stackoverflow.com/questions/940577/javascript-regular-expression-email-validation?noredirect=1&lq=1 – holmberd May 15 '17 at 14:37

2 Answers2

1

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

if(email.lastIndexOf("@") === 0 || !(email.endsWith("@yahoo.com") || email.endsWith("@gmail.com"))){
Lennholm
  • 7,205
  • 1
  • 21
  • 30
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.

dpellier
  • 1,029
  • 11
  • 9