For anyone who has spent a long time writing validation routines, verifying email addresses is a challenging task. In the good old days, a robust email pattern coded in a regular expression was, most of the time, good enough to make sure that a user had entered a well-formed email address. Now, things are different, considering the vast number of current email domains. However, in order to keep the method’s source code simple and readable, I’ll walk through an intermediate example, and instruct the method to check only for well-formed addresses and existing domains in the DNS. Its signature is as follows: public function validateEmail($field,$errorMessage){
As shown above, the method verifies whether the supplied email address is at least well-formed, without troubling things too much with complex patterns. It then searches in the DNS for the corresponding MX records, in order to determine whether the domain part corresponds to a real email domain. To perform this task, I use the “checkdnsrr()” PHP built-in function, which is extremely helpful when searching DNS records. Of course, this fact doesn’t mean that the user really exists, but it’s a decent way to check for the existence of a given email domain. From this point onward, you can make your own way either by improving the effectiveness of this method or writing a full-fledged alternative solution, in order to verify user-supplied email addresses. Now, in case you don’t know, the PHP “checkdnsrr()” function isn’t available on Windows systems, so here’s the alternative “windnsrr()”function, which essentially performs the same task on Microsoft servers: private function windnsrr($hostName,$recType=''){ And eventually, if you’re running your PHP applications on a Windows server, the “validateEmail()” method should be rewritten like this: public function validateEmail($field,$errorMessage){ After having defined the last checking method of the class, the only thing left to complete the definition of the form “validator” class consists of including two useful corollaries: the “checkErrors()” and “displayErrors()” methods.
blog comments powered by Disqus |