Cookie

We use cookies to improve your experience on our site, and to provide a live chat feature. To find out more please read our privacy policy.

Sample code for email validation

This page provides sample code to help you set up Postcoder email validation.

Copy any example below and then insert your own API key to make it work. Sign up to get an API key.

Email validation using JavaScript

This example uses the email endpoint to check whether an email address is valid and capable of receiving email. It can be customised using the config settings at the end of the HTML.

Email validation: Enable access on your API key using the Data Options page or by contacting us.
class PostcoderEmail{
  
  constructor(config) {
    this.config = config
    this.init()
  }

  init() {

    this.endpoint = 'https://ws.postcoder.com/pcw/' + this.config.apikey + '/emailaddress/'
    
    this.input = document.querySelector(this.config.searchterm)

    // add blur event listener to the email field, to call the search function
    this.input.addEventListener('blur', this.search)

    // create an empty div for the tick/cross and place it in the page
    this.successindicator = document.querySelector(this.config.successindicator)

    // create an empty div for the alternative email messasge and place it hidden in the page
    this.alternative = document.createElement('div')
    this.alternative.style.display = 'none'
    this.input.parentNode.insertBefore(this.alternative, this.input.nextSibling)

    // add a result container to the page, delete when not required.
    this.resultcontainer = document.createElement('pre')
    this.input.closest('form').appendChild(this.resultcontainer)

  }

  search = event => {

    //remove previous email validity indicator
    this.successindicator.classList.remove('isvalid','notvalid')

    //hide the alternaive email message
    this.alternative.style.display = 'none'

    if(this.input.value){

      let self = this
      let searchvalue = encodeURIComponent(this.input.value)

      // fetch the json formatted result from Postcoder and pass it to processResult
      fetch(this.endpoint + searchvalue)
        .then( response => {
          if (!response.ok) { 
            throw response 
          }
          return response.json()
        })
        .then( json => {
          self.processResult(json)
        })
        .catch( err => {

          if(typeof err.text === 'function'){
            err.text().then( errorMessage => {
              console.log('Postcoder request error ' + err.status + ' : ' + errorMessage)
            })
          }else{
            console.log(err)
          }
      })
    }
  }

  processResult = result =>{

    // display the email validity indicator
    if(result.valid === true){
      this.successindicator.classList.add('isvalid')
    }else{
      this.successindicator.classList.add('notvalid')
    }

    // display any alternative email suggestion
    if(result.alternative){
      this.alternative.innerHTML = 'Did you mean ' + result.alternative + '?'
      this.alternative.style.display = 'block'
    }

    // show result on page, delete when not required.
    this.resultcontainer.innerHTML = "Result: \n\n" + JSON.stringify( result, null, 4 )

  }

}
<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="postcoder.css" > 
    <script src="postcoder_email.js"></script>
  </head>
  <body>


    <form>

      <label for="txt_search">Email address</label>
      <div id="successindicator"></div>
      <div class="search_wrap">
        <input type="text" id="txt_search">
      </div>
    
    </form>


    <script>
        
        new PostcoderEmail({
          apikey: 'PCW45-12345-12345-1234X', 
          searchterm: '#txt_search', // query selector of the searchterm input field
          successindicator: '#successindicator', // query selector of the email valid/invalid indicator
        })

    </script>


  </body>
</html>
input, select {
	display: block;
	box-sizing: border-box;
	width: 100%;
	padding: 10px;
	height: 40px;
	margin-bottom: 0.5em;
	border-width: 1px;
	border-style: solid;
	border-color: lightgray;
}

.search_wrap {
	overflow: hidden;
}

.search_wrap div {
	font-size: 0.75em;
}

button {
	padding: 8px;
	margin-left: 0.5em;
	float:  right;
	font-family: sans-serif;
}

label {
	display: block;
	margin-top: 1.25em;
	margin-bottom: 0.25em;
}
select {
	position: relative;
	z-index: 1;
	padding-right: 40px;
}

.isvalid:after {
	content: '\2713';
	color: green;
}

.notvalid:after {
	content: '\2717';
    color: red;
}   

#successindicator {
	float:  right;
	margin-left: 0.5em;
	display: flex;
  	justify-content: center;
  	align-content: center;
  	flex-direction: column;
  	height: 40px;
}

#json_result_container {
	margin: 5em 0 0;
    background-color: #eee;
	color: #333;
    /* border: solid lightgrey 1px; */
	padding: 1em;
	overflow: auto;
}

#autocomplete_wrap{
	position: relative;
}

#suggestion_list{
	position:  absolute;
	background-color: #fff;
	outline: -webkit-focus-ring-color auto 1px;
	list-style-type: none;
  	margin: 0;
  	padding: 0;
  	max-height:  400px;
  	overflow-y: auto;
}

#suggestion_list li{
	cursor: pointer;
	padding: 10px 5px;
}

#suggestion_list li.header{
	border-bottom: 2px solid #ddd;
}

#suggestion_list li:hover, #suggestion_list li.selected{
	background-color: #ddd;
}

#suggestion_list li span.location{
	font-size: 0.75em;
	color: #666;
}

.arrow {
 	border: solid black;
	border-width: 0 3px 3px 0;
	display: inline-block;
	padding: 3px;
}

.left {
	margin-left: 3px;
	transform: rotate(135deg);
	-webkit-transform: rotate(135deg);
}

.address{
	height: 140px;
	margin: 8px;
}

.map {
	height: 300px;
	width: 100%;
}

body {
	font-family: sans-serif;
	padding: 0;
	margin: 0;
}
Download this example

Email validation using Python, PHP or C#

These examples show how to make a request to the email endpoint to check whether an email address is valid and capable of receiving email.

Email validation: Enable access on your API key using the Data Options page or by contacting us.
from urllib.parse import quote
import requests
import json

# Request parameters
api_key = "PCW45-12345-12345-1234X"
email = "sales@alliescomputing.com"

# Prepare request and encode user-entered parameters with %xx encoding
request_url = f"https://ws.postcoder.com/pcw/{api_key}/email/{quote(email, safe='')}"

# Send request
response = requests.get(request_url)

# Process response
if response.status_code == 200:
    json = response.json()
    print(json["valid"])
else:
    print(f"Request error: {response.content.decode()}")
// Request parameters
$api_key = "PCW45-12345-12345-1234X";
$email = "sales@alliescomputing.com";

// Prepare request and encode user-entered parameters with %xx encoding
$request_url = "https://ws.postcoder.com/pcw/$api_key/email/" . urlencode($email);

// Send request
$result = file_get_contents($request_url, false, stream_context_create(["http" => ["ignore_errors" => true]]));

// Process response
$status_line = $http_response_header[0];
preg_match("{HTTP\/\S*\s(\d{3})}", $status_line, $match);
$status_code = $match[1];

if ($status_code == 200) {
    $json = json_decode($result);
    echo($json->valid);
} else {
    echo("Request error");
}
using System;
using System.Threading.Tasks;
using System.Web;
using System.Net.Http;
using Newtonsoft.Json.Linq;
					
public class Program
{
	public static async Task Main()
	{
		// Request parameters
		string apiKey = "PCW45-12345-12345-1234X";
		string emailAddress = "sales@alliescomputing.com";

		// Prepare request and encode user-entered parameters with %xx encoding
		string requestUrl = $"https://ws.postcoder.com/pcw/{apiKey}/email/{HttpUtility.UrlEncode(emailAddress)}";

		using (HttpClient client = new HttpClient())
		{
			// Send request
			var response = await client.GetAsync(requestUrl);
			var responseContent = await response.Content.ReadAsStringAsync();

			// Process response
			if (response.IsSuccessStatusCode)
			{
				JObject responseJson = JObject.Parse(responseContent);
				Console.WriteLine($"{responseJson["valid"]}");
			}
			else
			{
				Console.WriteLine($"Request error: {responseContent}");
			}
		}
	}
}