Cookie

Cookie consent

We use some essential cookies to make this website work. We'd like to set additional cookies to help us measure your experience when you view and interact with the website.

Cookie policy

Sample code for mobile validation

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

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

Mobile validation using JavaScript

This example uses the mobile endpoint to check whether a mobile phone number is valid and capable of receiving calls and texts. It can be customised using the config settings at the end of the HTML.

Mobile validation: Enable access on your API key using the Features page or by contacting us.
class PostcoderMobile{
  
  constructor(config) {
    this.config = config
    this.init()
  }

  init() {

    this.endpoint = 'https://ws.postcoder.com/pcw/' + this.config.apikey + '/mobile/'

    this.input = document.querySelector(this.config.searchterm)

    // add blur event listener to the mobile 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)

    // 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 mobile validity indicator
    this.successindicator.classList.remove('isvalid','notvalid');

    if(this.input.value){

      let self = this
      let searchterm = this.input.value

      // fetch the json formatted result from Postcoder and pass it to processResult
      fetch(this.endpoint + searchterm)
        .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 mobile validity indicator
    if(result.valid === true){
      this.successindicator.classList.add('isvalid');
    }else{
      this.successindicator.classList.add('notvalid');
    }

    // 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_mobile.js"></script>
  </head>
  <body>


    <form>

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


    <script>
        
        new PostcoderMobile({
          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.extra-info {
	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

Mobile validation using Python, PHP or C#

These examples show how to make a request to the mobile endpoint to check whether a mobile phone number is valid and capable of receiving calls and texts.

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

# Request parameters
api_key = "PCW45-12345-12345-1234X"
mobile_phone_number = "07500123456"

# Prepare request and encode user-entered parameters with %xx encoding
request_url = f"https://ws.postcoder.com/pcw/{api_key}/mobile/{quote(mobile_phone_number, 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";
$mobile_phone_number = "07500123456";

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

// 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 mobilePhoneNumber  = "07500123456";

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

		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}");
			}
		}
	}
}