Sample code for 30+ languages & platforms
PowerShell Requires Chilkat v11.0.0+

Validate and format a phone number with Twilio Lookup

See more Twilio Examples

Use Basic Lookup v2 to check a national-format number and obtain its E.164 and national display formats. Supply the two-letter country code for a national number. The example requests only the basic fields.

Read the boolean valid field even when the HTTP request succeeds. When it is false, display any validation_errors that Twilio supplies. Numbering-plan validation does not establish reachability or control of a phone. To confirm control, send an SMS verification code.

Twilio documentation

Chilkat PowerShell Downloads

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

$success = $false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Load an API key for the Twilio account from private application configuration.
$http = New-Object Chilkat.Http
$http.RequireSslCertVerify = $true
$http.BasicAuth = $true
$http.Login = "YOUR_API_KEY_SID"
$http.Password = "YOUR_API_KEY_SECRET"

#  The phone number is one URL path segment. Percent-encode spaces and any leading +.
$number = New-Object Chilkat.StringBuilder
$number.Append("020 7946 0018")
$encoded = $number.Encode("url_rfc3986","utf-8")
if ($encoded -ne $true) {
    $("Could not encode the phone number.")
    exit
}

$url = New-Object Chilkat.StringBuilder
$url.Append("https://lookups.twilio.com/v2/PhoneNumbers/")
$url.Append($number.GetAsString())
$url.Append("?CountryCode=GB")
$resp = New-Object Chilkat.HttpResponse
$reply = New-Object Chilkat.JsonObject

$success = $http.HttpNoBody("GET",$url.GetAsString(),$resp)
if ($resp.StatusCode -eq 0) {
    $("No HTTP response from Twilio.")
    exit
}

$parsed = $reply.Load($resp.BodyStr)
if (($success -ne $true) -or ($resp.StatusCode -ne 200)) {
    $("Twilio returned HTTP " + $resp.StatusCode)
    if (($parsed -eq $true) -and ($reply.JsonTypeOf("code") -eq 2)) {
        $("Twilio error: " + $reply.IntOf("code") + "  " + $reply.StringOf("message"))
    }

    exit
}

if ($parsed -ne $true) {
    $("Expected a JSON response from Twilio.")
    exit
}

if ($reply.JsonTypeOf("valid") -ne 5) {
    $("The lookup response is missing the validity flag.")
    exit
}

if ($reply.BoolOf("valid") -ne $true) {
    $("The number is invalid for the specified country.")
    $i = 0
    while (($i -lt $reply.SizeOfArray("validation_errors"))) {
        $reply.I = $i
        $($reply.StringOf("validation_errors[i]"))
        $i = $i + 1
    }

    exit
}

if ($reply.JsonTypeOf("phone_number") -ne 1) {
    $("The lookup response is missing the E.164 number.")
    exit
}

$("E.164: " + $reply.StringOf("phone_number"))
$("National format: " + $reply.StringOf("national_format"))