I have a form and one of the input fields ask the user to input their email. However, I only want to accept @gmail.com and @outlook.com but my code only seems to accepts @outlook.com. Can anyone give some advice on my code?
$( "#email" ).change(function() {
if (this.value.length <= 0 ) {
email=0;
$(this).removeClass( 'success_class' );
$(this).addClass( 'error_class' );
document.getElementById("emailError").innerHTML = "You need to enter your email";
} else if (this.value.length > 200) {
email=0;
$(this).removeClass( 'success_class' );
$(this).addClass( 'error_class' );
document.getElementById("emailError").innerHTML = "The email is too big.";
} else if ((this.value.search('@outlook.com') == -1 || this.value.search('@gmail.com') == -1) || (this.value.length != this.value.search('@outlook.com')+12 ||this.value.length != this.value.search('@gmail.com')+10)) {
email=0;
$(this).removeClass( 'success_class' );
$(this).addClass( 'error_class' );
document.getElementById("emailError").innerHTML = "You must enter your Gmail or Outlook email";
} else {
email=1;
$(this).removeClass( 'error_class' );
$(this).addClass( 'success_class' );
document.getElementById("emailError").innerHTML = "";
}
});
This is happening because of the way you are checking for these domains. Look at this line:
else if ((this.value.search('@outlook.com') == -1 || this.value.search('@gmail.com') == -1)
Let's see what happens when someone enters '@gmail.com'. The first condition checking for the absence of '@outlook.com' returns true, and the code block is entered, without checking for '@gmail.com'. So it appears to not work.
Few ways you could fix this:
1) use a positive search result instead of negative.
if(this.value.search('@outlook.com') > -1 || this.value.search('@gmail.com') > -1) {
// code for correctly entered email
}
2) use a Regular Expression. From Sagar V's answer, a good one to use is:
/\@(gmail|outlook)\.com$/i
3) use a select box that forces the user to pick one domain. This isn't good UI/UX in my opinion because users may not be familiar with entering an email like this, and would probably type it all into your input anyway.
I would prefer the regular expression as it's easier to follow, when you understand what it's doing.