email validation not catching space

Why is this email validation script not stopping an email address like this: debs@gmail. com
Am i doing something wrong?
if (document.form1.E_mail.value != "") {
		var email = document.form1.E_mail.value;
	  AtPos = email.indexOf("@");
	  StopPos = email.lastIndexOf(".");
	  SpacePos = email.lastIndexOf(" ");
	  CommaPos = email.lastIndexOf(",");
	
	if (AtPos == -1 || StopPos == -1) {
		themessage = (themessage + "Not a valid email address" + '\n');
	
	}
	
		if (StopPos < AtPos) {
			themessage = (themessage + "Not a valid email address" + '\n');
		
		}
	
			
		if (StopPos - AtPos == 1) {
			themessage = (themessage + "Not a valid email address" + '\n');
		
		}
	
		if (SpacePos > 0 ) {
		themessage = (themessage + "Not a valid email address" + '\n');
			
		} 
	
	
		
		if (CommaPos > 0 ) {
		themessage = (themessage + "Not a valid email address" + '\n');
		
			} 
		
	}
	

Open in new window

rivkamakAsked:
Who is Participating?
 
skijCommented:
I recommend simplifying this with REGEX:
if (document.form1.E_mail.value != "") {
    var email = document.form1.E_mail.value;
    if(!/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.test(email)) alert('Not a Valid Email');
}

Open in new window

0
 
Tom BeckCommented:
Works in my test. Open your javascript console and view this jsfiddle.

http://jsfiddle.net/9p73sbfe/

On a side note, lots of email addresses have a period in the characters before the @ so you might want to rethink this part.
if (StopPos < AtPos) {
			themessage = (themessage + "Not a valid email address" + '\n');
		
		}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.