Add phone validation to your app
Summary#
Phone validation checks that a phone number exists and is well formed, and returns its country, location, line type and international format. Use it at sign-up or checkout to reject mistyped numbers and to see what kind of line you are dealing with.
When to use it / when not to#
Use it for:
- a phone number field at sign-up, checkout or account recovery
- you need the number in international (E.164-style) format before you store it or send an SMS
Do not use it for:
- You need to know whether the number is live on a network right now: use the HLR lookup below.
- You want to check an email address: Email validation.
Before you start#
- API key: read it from the environment variable
SCREENLYYID_API_KEYon your server only. Use atest_key for the sandbox and aprod_key for live. Never put it in browser or mobile code. See Get a test key. - Base URL:
https://api.screenlyyid.com. HTTPS only. - Activation and plan: The phone validation product (
phv) must be activated on the account. - Start with the Instance API. Every flow starts with
POST /api/v1/instance/create, listing this product's code (phv) inCustomerIntelligence. It returns aCorrelationIdthat you send asx-correlation-idon the product call, along withx-api-key. A product call can be accepted only once per correlation id: repeating it with the same id can return409 duplicate_correlation_id. Create a new instance for each check (for example one per checkout or per sign-up).
curl --request POST --url 'https://api.screenlyyid.com/api/v1/instance/create' \
--header "x-api-key: $SCREENLYYID_API_KEY" --header 'Content-Type: application/json' \
--data '{"GlobalScreening": [], "CustomerIntelligence": ["phv"]}'
# { "CorrelationId": "...", "webEnrolmentUrl": "..." } (webEnrolmentUrl is only used by the hosted identity verification flow)Use it on its own or stacked#
This product can be called on its own (one instance with just phv, as above) or stacked with other products for the same customer: list several product codes in the one instance call and send the same CorrelationId on each product's call. See Run several checks in one session. Example pairing: phone + email + address at sign-up (CustomerIntelligence: ["phv", "emv", "adv"]).
Document and selfie identity verification is not part of this product. It only goes through the Instance API and the hosted capture page: see Identity verification (mobile) and Identity verification (web). Do not use the direct identity verification endpoints.
Implementation steps#
- Create the instance in your server code, right before the check. Keep the
CorrelationIdwith your own record (the user, the order). Do this on the server. - Call the endpoint
POST /api/v1/phone-validatewithx-api-key,x-correlation-idand a JSON body (next section). In a typical app this is the sign-up or form-submit handler, before you create the account. - Read the response and apply the decision logic: the fields marked ★ are the ones to base a decision on.
- Act on the result: accept, ask the customer to correct their input, flag for review, or block. Store the
CorrelationIdand the outcome: it is your audit trail, and the same id shows the check in the dashboard. - Handle failures (below) so a provider outage never breaks your flow.
Request and response#
Request#
{
"PhoneNumber": "0412345678",
"CountryCode": "AU"
}| Field | Type | Meaning | Example |
|---|---|---|---|
PhoneNumber | string | The number, in international format, or in local format together with CountryCode or IpAdress. Required. | 0412345678 |
CountryCode | string | ISO 3166 alpha-2 country to assume for a local-format number. Maximum 2 characters. | US |
IpAdress | string | The customer's IP, used to guess the country of a local-format number. (The field name is spelled this way in the API.) | 203.0.113.7 |
Response#
{
"Valid": true,
"Country": "Australia",
"CountryCode": "AU",
"PrefixNetwork": "Optus",
"InternationalNumber": "+61412345678",
"Location": "Australia",
"LocalNumber": "0412 345 678",
"Type": "mobile",
"CurrencyCode": "AUD",
"InternationalCallingCode": "61",
"IsMobile": true,
"CountryCode3": "AUS"
}| Field | Type | Meaning | Example |
|---|---|---|---|
Valid | boolean | ★ Whether the number is valid. | true |
Type | string | ★ The line type reported by the provider. | (provider value) |
IsMobile | boolean | ★ Whether it is a mobile number. | true |
InternationalNumber | string | The number in international format. Store this. | +14155552671 |
CountryCode | string | Country of the number, ISO 3166 alpha-2. | US |
Location | string | Location of the number, where known. | |
PrefixNetwork | string | Network the prefix belongs to. |
★ = base your decision on this field.
Decision logic#
Validisfalse: reject the number and ask the customer to correct it.Validistrue: storeInternationalNumber, not what the customer typed.- Compare
CountryCodewith the customer's country and flag a mismatch for review if it matters to you. - If you will send an SMS, check
IsMobile. Decide what to do with other values ofTypeusing the values you see in your own traffic.
function phoneDecision(p, expectedCountry) {
if (!p.Valid) return { action: "reject", reason: "invalid_number" };
const flags = [];
if (expectedCountry && p.CountryCode !== expectedCountry) flags.push("country_mismatch");
if (needsSms && !p.IsMobile) flags.push("not_mobile");
return flags.length ? { action: "review", reason: flags, number: p.InternationalNumber } : { action: "accept", number: p.InternationalNumber };
}Errors and limits#
| Status | When | Body |
|---|---|---|
400 | A required field is missing or the body is not valid JSON | A problem-details object: {"type": "...", "title": "One or more validation errors occurred.", "status": 400, "errors": {"<Field>": ["The <Field> field is required."]}} |
401 | x-api-key is missing or malformed, or the product is not activated on the account | Empty body with a WWW-Authenticate header |
409 | The same x-correlation-id was already used for this product | {"error": "duplicate_correlation_id", "message": "Duplicate correlation id received."} |
500 | The upstream data provider failed | {"error": "internal_error", "message": "An unexpected error occurred"} |
No rate limit is documented for phone validation. Use a 15 second timeout, do not retry 4xx, retry a 500 or timeout at most once.
HLR lookup#
POST /api/v1/hlr-lookup asks the mobile network whether a number is live and which network it is on now. Use it when phone-validate is not enough, for example before an expensive SMS or to spot a recently ported number. It uses the same instance, headers and phv product. Send PhoneNumber (and CountryCode for a local-format number):
{"PhoneNumber": "+61412345678"}Example response:
{
"Country": "Australia",
"IsPorted": true,
"CountryCode": "AU",
"Mnc": "01",
"NumberType": "mobile",
"InternationalNumber": "+61412345678",
"OriginNetwork": "YES OPTUS (Singtel Optus Ltd)",
"RoamingCountryCode": "",
"Imsi": "5050100000",
"LocalNumber": "0412 345 678",
"Mcc": "505",
"HlrStatus": "ok",
"HlrValid": true,
"CurrentNetwork": "Telstra",
"Msin": "",
"IsRoaming": false,
"Location": "Australia",
"Msc": "",
"CurrencyCode": "AUD",
"InternationalCallingCode": "61",
"NumberValid": true,
"PortedNetwork": "Telstra",
"IsMobile": true,
"CountryCode3": "AUS"
}Fields to base a decision on: HlrValid and NumberValid (the number is live), HlrStatus (ok), IsMobile and NumberType, IsPorted, CurrentNetwork, OriginNetwork, IsRoaming. Treat HlrValid false as an unreachable number. HLR uses the same phv product as phone-validate. A repeat call for the same product with the same CorrelationId can be refused with 409 duplicate_correlation_id, so use a separate instance for each call.
Batch#
POST /api/v1/batch-phone-validate: Validate many numbers in one request, for example to clean a list.
[{"PhoneNumber": "+14155552671"}, {"PhoneNumber": "0412345678", "CountryCode": "AU"}]The body is a JSON array of the same objects as the single call. The ScreenlyyID API sets no maximum batch size in its code and the batch endpoint returns the provider's response unchanged, so send modest chunks and a generous timeout. Do not use batch in a live sign-up path.
Code#
Minimal working server-side code. It creates the instance, makes the call with a timeout and throws on a non-2xx response with the status and error body attached. The key is read from SCREENLYYID_API_KEY.
JavaScript (Node 18+, fetch)#
// server only: this reads your API key. Node 18 or later, no dependencies.
const API = "https://api.screenlyyid.com";
const apiKey = process.env.SCREENLYYID_API_KEY; // test_ while building, prod_ in production
if (!apiKey) throw new Error("SCREENLYYID_API_KEY is not set");
// Step 1: one instance per check. It lists this product's code and returns the CorrelationId.
export async function createInstance() {
const r = await fetch(`${API}/api/v1/instance/create`, {
method: "POST",
headers: { "x-api-key": apiKey, "Content-Type": "application/json" },
body: JSON.stringify({ GlobalScreening: [], CustomerIntelligence: ["phv"] }),
});
if (!r.ok) throw new Error(`instance/create failed (HTTP ${r.status})`);
const { CorrelationId } = await r.json(); // spelled exactly like this
return CorrelationId;
}
// Step 2: Phone validation checks that a phone number exists and is well formed, and returns its country, location, line type and international format
export async function validatePhone(phoneNumber, countryCode) {
const correlationId = await createInstance();
const r = await fetch(`${API}/api/v1/phone-validate`, {
method: "POST",
headers: { "x-api-key": apiKey, "x-correlation-id": correlationId, "Content-Type": "application/json" },
body: JSON.stringify({ PhoneNumber: phoneNumber, ...(countryCode && { CountryCode: countryCode }) }),
signal: AbortSignal.timeout(15000),
});
if (!r.ok) {
const error = new Error(`/phone-validate failed (HTTP ${r.status})`);
error.status = r.status;
error.body = await r.json().catch(() => null);
throw error;
}
return { correlationId, result: await r.json() };
}Python (requests)#
# server only: this reads your API key. Python 3.9 or later, pip install requests
import os
import requests
API = "https://api.screenlyyid.com"
API_KEY = os.environ["SCREENLYYID_API_KEY"] # test_ while building, prod_ in production
def create_instance():
"""Step 1: one instance per check. It lists this product's code and returns the CorrelationId."""
r = requests.post(
f"{API}/api/v1/instance/create",
headers={"x-api-key": API_KEY},
json={"GlobalScreening": [], "CustomerIntelligence": ["phv"]},
timeout=15,
)
r.raise_for_status()
return r.json()["CorrelationId"] # spelled exactly like this
def validate_phone(phone_number, country_code=None):
"""Step 2: Phone validation checks that a phone number exists and is well formed, and returns its country, location, line type and international format"""
correlation_id = create_instance()
r = requests.post(
f"{API}/api/v1/phone-validate",
headers={"x-api-key": API_KEY, "x-correlation-id": correlation_id},
json={"PhoneNumber": phone_number, **({"CountryCode": country_code} if country_code else {})},
timeout=15,
)
r.raise_for_status() # a requests.HTTPError carries r.status_code and r.json() for the error body
return correlation_id, r.json()Next.js route handler#
// app/api/validatePhone/route.js (Next.js App Router). The key is read on the server only.
import { validatePhone } from "@/lib/screenlyyid";
export const dynamic = "force-dynamic";
export async function POST(request) {
const input = await request.json();
try {
const { result } = await validatePhone(input);
return Response.json(result); // send the browser only what it needs, never the API key or the CorrelationId
} catch (e) {
// a provider outage or timeout must not break your own flow: decide fail-open or fail-closed here
return Response.json({ error: "check_unavailable", status: e.status ?? null }, { status: 502 });
}
}Test it#
The sandbox runs real lookups, so there are no special test numbers: use numbers you control.
| Input | Expected result |
|---|---|
| 0412345678 with CountryCode AU | Valid true, InternationalNumber +61412345678, Type mobile, IsMobile true, PrefixNetwork Optus. |
| +14155552671 | Valid true, CountryCode US, Type unknown, IsMobile false: a valid number can still have Type unknown. |
| abc | 200 with Valid false and empty fields: a bad number is not an HTTP error. |
Done when#
- [ ] The API key is read only on the server, from
SCREENLYYID_API_KEY - [ ] A new instance is created per check and its
CorrelationIdis sent asx-correlation-id - [ ]
Valid: falseblocks the form with a message that lets the customer fix the number - [ ]
InternationalNumberis what you store - [ ] Errors and timeouts do not block sign-up (a defined fallback applies)
- [ ] A test call returns
200with atest_key