Sample code for 30+ languages & platforms
Dart 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 Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

  // Assumes Chilkat is unlocked. See Global Unlock Sample.
  // Load an API key for the Twilio account from private application configuration.
  final http = CkHttp();
  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 +.
  final number = CkStringBuilder();
  number.append('020 7946 0018');
  try {
    number.encode('url_rfc3986', 'utf-8');
  } on ChilkatException {
    print('Could not encode the phone number.');
    return;
  }

  final url = CkStringBuilder();
  url.append('https://lookups.twilio.com/v2/PhoneNumbers/');
  url.append(number.getAsString());
  url.append('?CountryCode=GB');
  final resp = CkHttpResponse();
  final reply = CkJsonObject();

  success = true;
  try {
    http.httpNoBody('GET', url.getAsString(), resp);
  } on ChilkatException {
    success = false;
  }
  if (resp.statusCode == 0) {
    print('No HTTP response from Twilio.');
    return;
  }

  var parsed = true;
  try {
    reply.load(resp.bodyStr);
  } on ChilkatException {
    parsed = false;
  }
  if ((!success) || (resp.statusCode != 200)) {
    print('Twilio returned HTTP ${resp.statusCode}');
    if ((parsed) && (reply.jsonTypeOf('code') == 2)) {
      print('Twilio error: ${reply.intOf('code')}  ${reply.stringOf('message')}');
    }

    return;
  }

  if (!parsed) {
    print('Expected a JSON response from Twilio.');
    return;
  }

  if (reply.jsonTypeOf('valid') != 5) {
    print('The lookup response is missing the validity flag.');
    return;
  }

  if (!reply.boolOf('valid')) {
    print('The number is invalid for the specified country.');
    var i = 0;
    while (i < reply.sizeOfArray('validation_errors')) {
      reply.i = i;
      print(reply.stringOf('validation_errors[i]'));
      i++;
    }

    return;
  }

  if (reply.jsonTypeOf('phone_number') != 1) {
    print('The lookup response is missing the E.164 number.');
    return;
  }

  print('E.164: ${reply.stringOf('phone_number')}');
  print('National format: ${reply.stringOf('national_format')}');
}