{"id":1837,"date":"2009-06-08T03:05:27","date_gmt":"2009-06-08T07:05:27","guid":{"rendered":"http:\/\/teamtutorials.com\/?p=1837"},"modified":"2009-09-05T13:09:20","modified_gmt":"2009-09-05T17:09:20","slug":"validating-email-address-with-php-and-ajax","status":"publish","type":"post","link":"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax","title":{"rendered":"Validating Email Address with PHP and AJAX"},"content":{"rendered":"

This tutorial will walk you through checking for an e-mail to be valid as the user is filling out the form without having to reload the page. Bear in mind, that there is no way to make sure that we get an accurate working e-mail every time. All we can do is prevent users from using extremely random ones or for domains that don\u2019t exist. I was working on a form for a new website that is going to require users to create an account and was browsing the web to see what people use to validate e-mails, other than the obvious choice of running it through a reg-ex (regular expression), and I came across a site that showed me a feature of php that can be useful. The original post can be found over at David Walsh\u2019s website<\/a>. I think that using that this php function as well as a reg-ex and running them from an AJAX call should do the trick. So let\u2019s get started. You can get the images we will be using here. <\/a>First we will make the form that will call the functions. Since this will be our user account creator we\u2019ll call it adduser.php. (I\u2019m leaving out the default HTML\/CSS as you can do that however you like \u2013 you may also note that this file could be an HTML as there is no php in this section \u2013 this is just a part of the much larger file that I am working with (-:). <\/p>\n

\r\n<script type="text\/javascript" src="includes\/js\/validate_email.js"><\/script>\r\n\r\n<form method="post" action="register.php" name="user">\r\n<h2>User Creation<\/h2>\r\nUserName (Display Name):<input type="text" name="display_name" id="display_name"\/> <br \/>\r\nFirst Name:<input type="text" name="fname" id="name"\/><br \/>\r\nLast Name:<input type="text" name="lname" id="surname"\/><br \/>\r\nE-mail:<input type="text" name="email" id="email" onBlur="checkEmail()"\/><div id="emailflag" style="display:inline;"><img src="images\/failure.gif"><\/div><br \/>\r\nPassword:<input type="password" name="pass" id="pass"\/>\r\nConfirm PW:<input type="password" name="pass2" id="pass2" \/>\r\n<br  \/>\r\n<\/form>\r\n<\/pre>\n

Only a few things to note here: the onBlur command in the e-mail textbox is the first. This is going to call the email function (which is included in the script include at the beginning of the file) every time that textbox is tabbed or clicked away from. Also, note the div after the textbox, that contains the failure image now as we will use that ID to change the image later. Next, we need to create the php file that will actually do the validation when the AJAX calls it. Let\u2019s call this file validate_email.php. I\u2019ll break this one down a little to explain what\u2019s going on. <\/p>\n

\r\n<?php\r\nif (isset($_GET['email'])){\r\n\tisValidEmail($_GET['email']);\r\n}\r\n<\/pre>\n

This couple of lines simply checks for a variable to be set and if it is, calls the function to validate the address \u2013 this will prevent from someone going straight to this file or going to it with a blank string. As you can see we pass the value in the variable to the function. <\/p>\n

\r\nfunction isValidEmail($email)\r\n\t{\r\n\t$myReg="\/^[A-Za-z0-9\\._-]+@[A-Za-z0-9_-]+\\.([A-Za-z0-9_-][A-Za-z0-9_]+)$\/";\r\n\t\tif(preg_match($myReg, $email)){\r\n\t\t\tif(domain_exists($_GET['email']))\r\n\t\t\t{\r\n\t\t\t\techo("<img src=\\"images\/success.gif\\">");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\techo("<img src=\\"images\/failure.gif\\">");\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\techo("<img src=\\"images\/failure.gif\\">");\r\n\t\t}\r\n\t}\r\n<\/pre>\n

The function looks worse than it actually is due to the reg-ex. They can be a little confusing, but once you understand what it does, it\u2019s not that bad\u2026.but that is another tutorial. For now just know it checks the string that is passed to it to be formatted correctly. First we set the reg-ex and then we pass the address to it through the preg_match command. This will process the string to match the reg-ex and output true or false. If it passes validation, we then pass it to our function to check the MX record. If that passes we echo the path to success.gif (which is a green check-mark), otherwise we echo the path to failure.gif (which is a red x). Note that for these to work you will need to put the images in the proper locations or change the path to the images. Finally, in this file we need to create the domain_exists fcuntion that we called in the above section of code. <\/p>\n

\r\nfunction domain_exists($email,$record = 'MX')\r\n{\r\n\tlist($user,$domain) = split('@',$email);\r\n\treturn checkdnsrr($domain,$record);\r\n}\r\n?>\r\n<\/pre>\n

This simply runs the e-mail(after splitting the email at the @ symbol) through the checkdnsrr which checks for the MX record to be retrievable from the domain name. This essentially just checks for a server to be responding at that domain name. Technically we could still put an e-mail that doesn\u2019t exist, as all we check is for the domain to exist. Next, we need to create the AJAX call file. We\u2019ll call this file validate_email.js.<\/p>\n

\r\nfunction checkEmail(){\r\n\thttpObject = getHTTPObject();\r\n\tif (httpObject != null) {\r\n\t\tif (!document.getElementById('email').value== ""){\r\n\t\t\thttpObject.open("GET", "..\/includes\/php\/validate_email.php?email="+document.getElementById('email').value, true);\r\n\t\t\thttpObject.send(null);\r\n\t\t\thttpObject.onreadystatechange = setImage;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tdocument.getElementById('emailflag').innerHTML = "<img src=\\"images\/failure.gif\\">";\r\n\t\t}\r\n\t}\r\n}\r\n<\/pre>\n

This file has 3 functions in it. The first one is the function that we are calling from the form in the first file. This function calls the getHTTPObject function to initialize the AJAX call that we will use. Next, we check for the email field in the form to contain information and if it does, we do an HTTP GET request to call the php file and pass it the email that is currently in the textbox. If it contains no data it sets the div that is created right after the textbox to contain the failure image. Once the HTTP object state changes, we call the function that will pass the image contents. <\/p>\n

\r\nfunction getHTTPObject(){\r\nif (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");\r\nelse if (window.XMLHttpRequest) return new XMLHttpRequest();\r\nelse {\r\nalert("Your browser does not support AJAX.");\r\nreturn null;\r\n}} \r\n<\/pre>\n

This function declares the httpObject that we will be using and throws an error in the browser if it does not support the call. <\/p>\n

\r\nfunction setImage(){\r\nif(httpObject.readyState == 4){\r\ndocument.getElementById('emailflag').innerHTML = httpObject.responseText;\r\n}}\r\n<\/pre>\n

This final function checks for the state of the object to be 4 (completed) and if it is it sets the innerHTML of the ID from the form to whatever was echoed from the PHP file (either the success or the failure gif). That completes the files. Ensure that all the files are in the right place. I have my php file in \/includes\/php\/validate_email.php and the javascript file is \/includes\/js\/validate_email.js. <\/p>\n

\"ajax_php_email_validation_01\"<\/p>\n

This is the form that should be shown when you go to the main form. <\/p>\n

\"ajax_php_email_validation_02\"<\/p>\n

When you type a valid e-mail into the e-mail box, the checkmark should appear where the X was like above.<\/p>\n

\"ajax_php_email_validation_03\"<\/p>\n

If you put in a improperly formatted e-mail like above, it should switch it back to an X. It will also go back to an X if you blank out the text box. <\/p>\n

That completes this tutorial. Some of this can be hard to follow so please leave any questions or comments you have in the comments sections and we\u2019ll help you out where we can. Also, I made the reg-ex fit as many things as I could, if you find a valid e-mail that it fails, please let me know so that I can modify it to work. Thanks for viewing this tutorial and I hope it was easy to follow. <\/p>\n","protected":false},"excerpt":{"rendered":"

This tutorial will walk you through checking for an e-mail to be valid as the user is filling out the form without having to reload the page.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[92,30,46,24,17],"tags":[],"yoast_head":"\nValidating Email Address with PHP and AJAX<\/title>\n<meta name=\"description\" content=\"This tutorial will walk you through checking for an e-mail to be valid as the user is filling out the form without having to reload the page.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Mike Maguire\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/teamtutorials.com\/#website\",\"url\":\"https:\/\/teamtutorials.com\/\",\"name\":\"Team Tutorials\",\"description\":\"Learn something new today\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/teamtutorials.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"http:\/\/teamtutorials.com\/wp-content\/uploads\/2009\/06\/ajax_php_email_validation_01.jpg\",\"contentUrl\":\"http:\/\/teamtutorials.com\/wp-content\/uploads\/2009\/06\/ajax_php_email_validation_01.jpg\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax#webpage\",\"url\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax\",\"name\":\"Validating Email Address with PHP and AJAX\",\"isPartOf\":{\"@id\":\"https:\/\/teamtutorials.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax#primaryimage\"},\"datePublished\":\"2009-06-08T07:05:27+00:00\",\"dateModified\":\"2009-09-05T17:09:20+00:00\",\"author\":{\"@id\":\"https:\/\/teamtutorials.com\/#\/schema\/person\/eb38d967529dbe49f7cbe082fd39105b\"},\"description\":\"This tutorial will walk you through checking for an e-mail to be valid as the user is filling out the form without having to reload the page.\",\"breadcrumb\":{\"@id\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/teamtutorials.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Validating Email Address with PHP and AJAX\"}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/teamtutorials.com\/#\/schema\/person\/eb38d967529dbe49f7cbe082fd39105b\",\"name\":\"Mike Maguire\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/teamtutorials.com\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/36f2aa9a11241ca79ed05e758e36f3cb?s=96&d=mm&r=r\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/36f2aa9a11241ca79ed05e758e36f3cb?s=96&d=mm&r=r\",\"caption\":\"Mike Maguire\"},\"sameAs\":[\"http:\/\/mikemaguire.me\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Validating Email Address with PHP and AJAX","description":"This tutorial will walk you through checking for an e-mail to be valid as the user is filling out the form without having to reload the page.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax","twitter_misc":{"Written by":"Mike Maguire","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebSite","@id":"https:\/\/teamtutorials.com\/#website","url":"https:\/\/teamtutorials.com\/","name":"Team Tutorials","description":"Learn something new today","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/teamtutorials.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax#primaryimage","inLanguage":"en-US","url":"http:\/\/teamtutorials.com\/wp-content\/uploads\/2009\/06\/ajax_php_email_validation_01.jpg","contentUrl":"http:\/\/teamtutorials.com\/wp-content\/uploads\/2009\/06\/ajax_php_email_validation_01.jpg"},{"@type":"WebPage","@id":"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax#webpage","url":"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax","name":"Validating Email Address with PHP and AJAX","isPartOf":{"@id":"https:\/\/teamtutorials.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax#primaryimage"},"datePublished":"2009-06-08T07:05:27+00:00","dateModified":"2009-09-05T17:09:20+00:00","author":{"@id":"https:\/\/teamtutorials.com\/#\/schema\/person\/eb38d967529dbe49f7cbe082fd39105b"},"description":"This tutorial will walk you through checking for an e-mail to be valid as the user is filling out the form without having to reload the page.","breadcrumb":{"@id":"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/teamtutorials.com\/web-development-tutorials\/validating-email-address-with-php-and-ajax#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/teamtutorials.com\/"},{"@type":"ListItem","position":2,"name":"Validating Email Address with PHP and AJAX"}]},{"@type":"Person","@id":"https:\/\/teamtutorials.com\/#\/schema\/person\/eb38d967529dbe49f7cbe082fd39105b","name":"Mike Maguire","image":{"@type":"ImageObject","@id":"https:\/\/teamtutorials.com\/#personlogo","inLanguage":"en-US","url":"https:\/\/secure.gravatar.com\/avatar\/36f2aa9a11241ca79ed05e758e36f3cb?s=96&d=mm&r=r","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/36f2aa9a11241ca79ed05e758e36f3cb?s=96&d=mm&r=r","caption":"Mike Maguire"},"sameAs":["http:\/\/mikemaguire.me"]}]}},"_links":{"self":[{"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/posts\/1837"}],"collection":[{"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/comments?post=1837"}],"version-history":[{"count":0,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/posts\/1837\/revisions"}],"wp:attachment":[{"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/media?parent=1837"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/categories?post=1837"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/teamtutorials.com\/wp-json\/wp\/v2\/tags?post=1837"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}