Validate UAE phone numbers and send OTP SMS
Validate and normalize the destination on your server before sending an OTP through Twilio or an approved regional SMS provider.
1. Validate and normalize the number
Supply an international-format number such as +971501234567. The Node.js and Python helpers below forward input unchanged. Convert local input such as 0501234567 (replace the leading 0 with +971) or an international dialling prefix such as 00971501234567 (replace the leading 00 with +) before calling the API. Validation does not perform these conversions: both unconverted inputs return valid: false, so the helpers reject them before sending SMS.
POST a phone number in the JSON body to /api/v1/phone/validate, using a key with the validation:phone scope. Check valid, type, and country.code; use formats.e164 as the gateway destination. For a UAE mobile, the response type is mobile. A UAE carrier is included when its original number prefix maps to a known operator.
{ "data": { "valid": true, "formats": { "e164": "+971501234567" }, "country": { "code": "AE" }, "type": "mobile", "carrier": { "name": "e& (Etisalat)", "mcc": "424", "mnc": "02", "type": "mno" }, "portingNote": "Carrier is based on original number allocation. Number may have been ported to a different carrier." }}2. Node.js with Twilio
Install the provider SDK with npm install twilio. Set the account credentials, KhaleejiAPI key, and a UAE sender approved for your Twilio account and route in server-side environment variables. The helper functions in the example are application storage and rate-limit integrations, not built-in SDK methods.
import { randomInt } from "node:crypto"import twilio from "twilio" const twilioClient = twilio( process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN,) export async function sendUaeOtp(rawPhone, requestIp) { // Apply an IP limit before validation and a destination limit before sending. await enforceOtpRateLimit({ ip: requestIp }) const response = await fetch("https://khaleejiapi.dev/api/v1/phone/validate", { method: "POST", headers: { Authorization: "Bearer " + process.env.KHALEEJI_API_KEY, "Content-Type": "application/json", }, body: JSON.stringify({ phone: rawPhone }), signal: AbortSignal.timeout(3000), }) if (!response.ok) throw new Error("Phone validation is unavailable") const { data } = await response.json() if ( data.valid !== true || data.type !== "mobile" || data.country?.code !== "AE" || !data.formats?.e164 ) { throw new Error("Enter a valid UAE mobile number") } await enforceOtpRateLimit({ ip: requestIp, phone: data.formats.e164 }) const code = randomInt(0, 1_000_000).toString().padStart(6, "0") // App-specific helper: persist a keyed hash, expire it after 5 minutes, // and consume it once after a successful, attempt-limited verification. await saveOtpForVerification(data.formats.e164, code, 300) const message = await twilioClient.messages.create({ to: data.formats.e164, from: process.env.TWILIO_APPROVED_SENDER, body: `Your verification code is ${code}. It expires in 5 minutes.`, }) return { messageId: message.sid }}3. Python with Twilio
Install the dependencies with pip install requests twilio. Keep the same server-side validation gate and use the normalized E.164 destination for the send.
import osimport secrets import requestsfrom twilio.rest import Client twilio_client = Client( os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"],) def send_uae_otp(raw_phone, request_ip): # Apply an IP limit before validation and a destination limit before sending. enforce_otp_rate_limit(ip=request_ip) response = requests.post( "https://khaleejiapi.dev/api/v1/phone/validate", headers={"Authorization": "Bearer " + os.environ["KHALEEJI_API_KEY"]}, json={"phone": raw_phone}, timeout=3, ) response.raise_for_status() data = response.json().get("data", {}) if ( data.get("valid") is not True or data.get("type") != "mobile" or data.get("country", {}).get("code") != "AE" or not data.get("formats", {}).get("e164") ): raise ValueError("Enter a valid UAE mobile number") enforce_otp_rate_limit(ip=request_ip, phone=data["formats"]["e164"]) code = f"{secrets.randbelow(1_000_000):06d}" # App-specific helper: persist a keyed hash, expire it after 5 minutes, # and consume it once after a successful, attempt-limited verification. save_otp_for_verification(data["formats"]["e164"], code, ttl_seconds=300) message = twilio_client.messages.create( to=data["formats"]["e164"], from_=os.environ["TWILIO_APPROVED_SENDER"], body=f"Your verification code is {code}. It expires in 5 minutes.", ) return {"message_id": message.sid}4. Choosing Twilio, e&, or du routes
- KhaleejiAPI reports an original-prefix carrier hint, not a live lookup of the subscriber's current network. UAE number portability means an e& or du label can be stale. Treat
carrier.mccandcarrier.mncas optional routing or analytics hints only. - Twilio and direct operator messaging are separate integrations. Confirm UAE destination coverage, approved sender identity, OTP traffic eligibility, delivery receipts, and current route availability with your selected provider before launch.
- For a direct e& or du connection, obtain the operator's current A2P onboarding, API contract, credentials, sender approval, throughput limits, and delivery callback requirements. Implement that documented contract in a provider adapter; there is no universal e&/du gateway endpoint or request schema to copy here.
- Choose a route using provider-supported routing and observed delivery results. Do not retry an accepted message blindly across gateways; use an idempotent attempt reference and delivery status to avoid duplicate OTPs.
5. Protect the OTP flow
- Rate-limit before sending by IP and normalized destination; add a bot challenge and restrict destinations to the countries you serve.
- Generate codes with a cryptographically secure random generator. Store a keyed hash, expire codes quickly, cap verification attempts, and invalidate a code after successful use.
- Do not return or log codes, API keys, or full phone numbers. Keep gateway callbacks authenticated and treat a provider's accepted response as queued, not delivered.
- Register and verify the sender and message category for the intended UAE route. See GCC SMS sender ID compliance before sending production traffic.