Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Non-RegExp Email Validation Script

Validation

Non-RegExp Email Validation Script

by  BillyRayPreachersSon  Posted    (Edited  )
If you are looking for an email validation script that doesn't require RegExp (and would therefore be easier to understand if you don't know RegExp very well, like myself), consider something like this:

Code:
function validateEmailAddress(emailToValidate) {
	if (emailToValidate == '' || typeof(emailToValidate) == 'undefined') return(false);
	emailToValidate = stringTrim(emailToValidate);
	
	var emailLength = emailToValidate.length;
	var atPos = emailToValidate.indexOf('@');
	var firstDotPos = emailToValidate.indexOf('.');
	var lastDotPos = emailToValidate.lastIndexOf('.');
	
	if (emailLength < 7) return(false);				// minimum email address length ("x@xx.xx")
	if (atPos < 1) return(false);					// traps for no @, or @ as first character
	if (firstDotPos < 1) return(false);				// traps for no ., or . as first character
	if (atPos == emailLength-1) return(false);		// traps for @ as penultimate or last character
	if (lastDotPos >= emailLength-2) return(false);	// traps for too few digits after last . (must be at least 2)
	// traps for @ character next to . character
	if (emailToValidate.charAt(atPos-1) == '.' || emailToValidate.charAt(atPos+1) == '.') return(false);
	return(true);			
}

I just find this sort of thing much easier to (a) understand and (b) modify without RegExp knowledge.

It may not be 100% effective against all email addresses, but will probably trap 99% of common mistakes (much like the RegExp version, IMHO).

Dan


[link http://www.coedit.co.uk/][color #00486F]Coedit Limited[/color][/link][color #000000] - Delivering standards compliant, accessible web solutions[/color]

[tt]Dan's Page [blue]@[/blue] Code Couch
http://www.codecouch.com/dan/[/tt]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top