Tag: mail validation

Validate email address

Posted by on July 18, 2010

Once in a while you’ll be forced to validate an email address (or many!) — The usual no-brainer method is to perform a quick syntactical test to ensure the address is not malformed, however even a properly formed address may be invalid or, unreachable.

Clearly we must add a second validation step… — Hey I know, let’s check the MX records!

Procedure.s Email_GetHost( eMail.s )
	If eMail
		ProcedureReturn Right( eMail, Len(eMail) - FindString(eMail, "@", 1) )
	EndIf
EndProcedure
 
Procedure.i Email_ValidateAddress( eMail.s, CompleteValidation.i = #True )
 
	Define.s pattern = "^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"
	Define.i is_valid = #False
 
	Define.i handle = CreateRegularExpression( #PB_Any, pattern )
	If IsRegularExpression( handle )
 
		If MatchRegularExpression( handle, eMail )
			If CompleteValidation
 
				Dim mx.s(99)
				If getmxrr( Email_GetHost(eMail), mx() ) ; see http://gushh.net/blog/2010/07/17/get-mx-records/
					is_valid = #True
				EndIf
 
			Else
				is_valid = #True
			EndIf
		Else
				is_valid = -1
		EndIf
 
		FreeRegularExpression( handle )
	EndIf
 
	ProcedureReturn is_valid
 
EndProcedure

For the getmxrr() function click here. Or click here for the full code + example usage

The full code also contains a few other helper routines, I left them in there in case someone finds them useful.

These are the functions included in the source:

Email_GetName()
Email_GetHost()
Email_ValidateAddress()
Email_ConvertToLiteral()

Obviously you’ll have to tweak a bit the code, specially the way it handles the arrays. But overall it should be pretty usable. I might come up with a cross-platform version in the future, but so far I haven’t found a need for it.

Please double-check the example code, make sure you understand the routine could return <= 0 if validation fails (two modes basically, syntax fault and mx fault).

Feel free to leave a comment or send me your own version of the code!

Cheers!