Tag: array

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!

Randomize Array – A Flexible hard-coded macro

Posted by on June 13, 2009

Tired of writing the same “randomize array” routines over and over?, just snap this little macro and register them as you see fit. A guard should be put to avoid double registrations (although the compiler will complain about this anyway — I suggest registering right after you include this, since you already know what you’re going to need… )

Code:
http://gushh.net/dev/?file=pb/randomizearray.pb

Examples:
http://gushh.net/dev/?file=pb/randomizearray_test.pb

Simple, right?

A need for both a debug / format (to string) and random fills for string arrays is present, but I’m not in the need of them at the moment. Do request if you need them though.

Cheers.