Reputation: 190
I'm making an email validation system for one of my projects and all was working fine until I bumped into the error that if the email followed the structure:
username.domain@domain-ext
then it would return TRUE. So is there a way to check if the '@' comes before the '.' in vanilla javascript?
here is the code:
function validate ( element ) {
if( element.indexOf ( '@' ) > -1 && element.indexOf ( '.' ) > -1 ){
//checks if there is anything between '@' and '.'
var domain_name = element.substring(
element.lastIndexOf("@") + 1,
element.lastIndexOf(".")
);
if (domain_name != '')
{
//checks if there is anything before the '@'
var username = element.split('@')[0];
if (username != '') {
//checks if there is anything after the '.'
var emailsplit = element.split('.');
var domain = emailsplit[emailsplit.length - 1];
if (domain != '')
{
return true;
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
console.log('[email protected] : ' + validate('[email protected]'));
console.log('@domain.com : ' + validate('@domain.com'));
console.log('[email protected] : ' + validate('[email protected]'));
console.log('username@domain. : ' + validate('username@domain.'));
console.log('usernamedomaincom : ' + validate('usernamedomaincom'));
console.log('username.domain@com : ' + validate('username.domain@com'));
Upvotes: 0
Views: 487
Reputation: 190
I just needed to add 1 more if statement using the lastIndexOf. Thank you @jabaa
function validate ( element ) {
if( element.indexOf ( '@' ) > -1 && element.indexOf ( '.' ) > -1 ){
if ( element.indexOf('@') < element.lastIndexOf('.') )
{
//checks if there is anything between '@' and '.'
var domain_name = element.substring(
element.lastIndexOf("@") + 1,
element.lastIndexOf(".")
);
if (domain_name != '')
{
//checks if there is anything before the '@'
var username = element.split('@')[0];
if (username != '') {
//checks if there is anything after the '.'
var emailsplit = element.split('.');
var domain = emailsplit[emailsplit.length - 1];
if (domain != '')
{
return true;
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false
}
}
else {
return false;
}
}
console.log('[email protected] : ' + validate('[email protected]'));
console.log('@domain.com : ' + validate('@domain.com'));
console.log('[email protected] : ' + validate('[email protected]'));
console.log('username@domain. : ' + validate('username@domain.'));
console.log('usernamedomaincom : ' + validate('usernamedomaincom'));
console.log('username.domain@com : ' + validate('username.domain@com'));
Upvotes: 1