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.
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.classList.add('show')
this.resultcontainer.innerHTML = "Result: \n\n" + JSON.stringify( result, null, 4 )
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="postcoder_email.css" />
<script src="postcoder_email.js"></script>
</head>
<body>
<h1>Postcoder: Email validation example</h1>
<form>
<label for="txt_search">Email address</label>
<div class="search_wrap">
<input type="text" id="txt_search" />
<div id="successindicator"></div>
</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>
/* Heading style */
h1 {
font-size: 1.17rem;
}
/* Form labels */
label {
display: block;
margin-block: 1.25rem 0.25rem;
}
/* General form inputs */
input {
display: block;
box-sizing: border-box;
width: 100%;
padding: 10px;
height: 40px;
margin-block-end: 0.5rem;
border: solid lightgray 1px;
}
/* Postcode/address input and button wrapper */
.search_wrap {
display: flex;
}
/* Postcode/address text input - Remove margin-block-end */
.search_wrap #txt_search {
margin: 0;
}
/* Icon to show if the email address entered is correct or incorrect */
#successindicator {
display: flex;
justify-content: center;
align-items: center;
font-size: 1.5rem;
font-weight: bold;
line-height: 1rem;
}
#successindicator.isvalid,
#successindicator.notvalid {
width: 2.5rem;
}
.isvalid:after {
content: "\2713";
color: green;
}
.notvalid:after {
content: "\2717";
color: red;
}
/* Bank account validation results */
form pre {
display: none;
background-color: #eee;
border: dashed #ccc 1px;
padding: 0.75rem;
white-space: pre-wrap;
}
form pre.show {
display: block;
}
/* Set the body tag defaults */
body {
font-family: sans-serif;
padding: 0;
margin: 0;
}
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.
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}");
}
}
}
}