0

I had created an registration form in which i had created and email i had provided validation to all the filed but I'm confused how to give validation to email field because i want that email should be either gmail.com or yahoomail.com if some one enters any other email even yahoomail.co.in it should give error message. here is the code i which checking that its having @ and . in the email or not

var atdrate=email.indexOf("@");
var dot1=email.indexOf(".");

else if(atdrate<1 || dot1<1)
    {
        alert("Enter valid Email");
        if(gml<atdrate+1)
            alert("Enter  a vaild mail id");
        else if(yml<atdrate+1)
            alert("Enter a valid email id");

    }
neerav shah
  • 27
  • 1
  • 7

1 Answers1

1

Using Regular Expressions is probably the best way. Here's an example (live demo):

function validateEmail(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 

But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.

*answer from https://stackoverflow.com/a/46181/1521984

Update: Then use the JavaScript split() function to split the mail address after the '@' and check the value versus your strings.

var mail = yourMailAdress.split("@");
if (mail[1] == "gmail.com" || mail[1] == "yahoomail.com") {
    // OKAY
} else {
    // false
}
Community
  • 1
  • 1
F481
  • 990
  • 8
  • 22
  • but using regular expression will validate all type of email i want that it should only have gmail.com or yahoomail.com after @ sign – neerav shah Jun 06 '13 at 07:30
  • then simply put the hosters (gmail.com, yahoomail.com) in your regex after the '@' – F481 Jun 06 '13 at 07:34
  • thanks for your answer but i don't want to use regular expression i want to try it without using regularexpression – neerav shah Jun 06 '13 at 07:51
  • hey F481 i wrote the code which u gave me in this wave email=xyz@yahoomail.com mail=email.split("@") frmt1='yahoomail.com' and frmt2='gmail.com' else if(mail[1]!=frmt1 || mail[1]!=frmt2) { alert("Enter valid Email"); } its not give alert window that enter valid email can you tell whats wrong or where im laking – neerav shah Jun 06 '13 at 09:57
  • Recheck your code! The 'else'-clause is wrong there. Perhaps you can debug the script with [firebug](https://getfirebug.com/)? – F481 Jun 06 '13 at 10:25
  • on the top of my answer, on the left side you can see a hook (under the 0). When you check/click this hook, you're done! :) – F481 Jun 07 '13 at 07:26
  • Please note that deactivating JavaScript on iOS will not affect your cordova apps. They are still able to run JavaScript, even if it is deactivated in your settings. – Sithys May 26 '15 at 12:50