Trestle - Identity Data Enrichment and Validation APIs Trestle - Identity Data Enrichment and Validation APIs Trestle - Identity Data Enrichment and Validation APIs Trestle - Identity Data Enrichment and Validation APIs
  • Products
        • Enrichment

        • Reverse Phone APIGLOBAL
        • Verify and enrich phone numbers
        • Reverse Address API
        • Verify and enrich address information
        • Caller Identification API
        • Identify and enrich caller information
        • Add-Ons

        • Litigator Check
        • Identify phone numbers associated with serial litigators
        • Email Deliverability
        • Confirm email inboxes accept mail in real-time
        • Spam Check
        • Flag phone numbers tied to high-risk calling activity
        • Email Age Score
        • Score how long an email has existed
        • Validation & Verification

        • Phone Validation APIGLOBAL
        • Validate phone numbers and identify disconnected numbers
        • Real Contact API
        • Verify phone, email, and address information
        • Address Validation API
        • Validate and normalize addresses
        • Assess Risk

        • Decision Console
        • Optimize identity verification for manual review
        • Decision Signals API
        • Automate identity verification for risk decisioning
        • Start using Trestle products today

          Get started for free—no credit card required

          Start Your Free Trial

  • Solutions
        • Industries

        • B2B Contact Data
        • eCommerce
        • Insurance
        • Lead Generation
        • Real Estate
        • Communications
        • Use Cases

        • Verify and Prioritize Leads
        • Outbound Dialing Optimization
        • Assess Risk And Prevent Fraud
        • Inbound Call Routing and Verification​
        • Signup and Onboarding​
        • Optimize AI Voice Agents
        • Start using Trestle products today

          Get started for free—no credit card required

          Start Your Free Trial

  • Pricing
  • Resources
        • API Documentation
        • Blog
        • Knowledge Base
        • Case Studies
        • Glossary
        • Partners and Integrations
  • Company
        • About Us
        • Why Trestle
        • Careers
        • Affiliate Program
        • Contact
  • Log In
  • Start for Free

Trestle Overview

19
  • Does Trestle Offer DNC Checks?
  • Does Trestle Have a Sandbox Environment To Test Integrations?
  • What is Trestle’s Coverage and Accuracy?
  • Which Countries’ Data Do You Have?
  • Does Trestle Normalize Phone Number Format?
  • How Do You Integrate Trestle’s APIs?
  • How Does Trestle’s API Pricing Work?
  • How Often is Trestle’s Data Updated?
  • How to Properly Sample a Test File and Evaluate Trestle
  • Understanding NPA-NXX and the Implications of Number Portability
  • Understanding Trestle’s Free API Trial and the API Access Request Process for Specific Products
  • What are the Response Times for Trestle’s APIs?
  • What are the Various Sources of Trestle’s Identity Data?
  • What are Trestle’s SLAs?
  • What Demographic Data Does Trestle Have?
  • What Is Our Global Phone Validation Coverage?
  • What is the Default and Max QPS Supported?
  • What Queries are Billable?
  • What Security Measures are Taken by Trestle?

Product Features

39
  • Everything to Know About Source ID
  • Everything to Know About IP Trust Scores
  • How to Check When an Email Address Was Made
  • Everything to Know About Spam Checks
  • Using IP Intelligence Checks to Verify Lead Legitimacy in Real Contact API
  • Everything to Know About Phone-to-Address Match
  • Real Contact API 1.1 vs. Real Contact API 2.0: What’s Changed and How to Upgrade
  • Everything to Know About Phone Activity Score
  • Everything to Know About Real Contact API 2.0
  • How Trestle’s Activity Score is Different From HLR Lookups
  • Everything To Know About Name Match Details
  • Everything To Know About Phone-to-Name Confidence Score
  • Everything To Know About Litigator Checks
  • Everything To Know About the Email Age Score Add-on
  • Everything To Know About the Email Deliverability Add-on
  • Explain Real Contact API Grading
  • Fine-Tuning Find Person API Results
  • How Can Trestle’s Email Data Be Used?
  • How Do I Determine Phone Validity?
  • How Do You Read Trestle’s Phone Activity Score?
  • How Does Our Real Contact API Name Matching Work?
  • How Does Trestle Assess Email Validity in Real Contact?
  • How is Trestle’s Phone Activity Score Calculated?
  • How To Read the Real Contact Data Assessment Report
  • International Reverse Phone API Explained
  • Line Type Fidelity and Confidence
  • Trestle API Response Attribute Ranking
  • Trestle Warnings – A Comprehensive Guide
  • Understanding the Difference: Phone Validity vs. Trestle’s Activity Score
  • What are the Different Address Types Returned by Trestle?
  • What Does a Name Match of Null Mean?
  • What Does the Carrier Name Mean?
  • What is the Difference Between CNAM and Trestle’s Smart CNAM API?
  • What is the Difference Between Fixed VoIP and Non-fixed VoIP?
  • What is the Difference Between Reverse Phone API, Caller Identification API, and Smart CNAM API?
  • What is the Link Date Associated with Phones and Addresses?
  • Why and When to Use Trestle’s Name Hint
  • Why Do We Return a Maximum of 100 Entities in Find Person API?
  • Why Does the Address Return as Invalid?

Integrations

22
  • HubSpot | Phone Validation App Integration Guide
  • ZoomInfo | Phone Validation, Real Contact, and Reverse Phone Integration Guide
  • Databar | Phone Validation Integration Guide
  • Make | Real Contact API Integration Guide
  • Make | Phone Validation API Integration Guide
  • Apollo | Phone Validation Integration Guide
  • HighLevel | Phone Validation Integration Guide
  • boberdoo | Real Contact API Integration Guide
  • Clay | Validate Phone Number Integration Guide
  • Clay | Verify Contact Integration Guide
  • HubSpot | Real Contact Phone Grading App Integration Guide
  • How Do I Use a HubSpot List To Grade My Contacts?
  • How Do I Use HubSpot Workflow Triggers To Grade My Contacts?
  • Lead Prosper | Phone Validation Integration Guide
  • Lead Prosper | Real Contact Integration Guide
  • Reverse Phone API Enrichment of Leads in Google Sheets via Zapier
  • Snowflake | Phone Validation Integration Guide
  • What is the Phone Validation Integration within ActiveProspect?
  • What is the Real Contact Integration within ActiveProspect?
  • Validate and Verify Leads with Trestle’s Phone Validation API in Sierra Interactive via Zapier
  • Validate Leads with Trestle’s Phone Validation API in LeadConnector via Zapier
  • Zapier | Grade Leads from a Google Sheet with Real Contact

Troubleshooting

9
  • How to Prevent 429 Errors by Sizing API Concurrency to Your QPS Limit
  • How to Fix 403 Forbidden Errors When Using Trestle’s APIs
  • Why Won’t My Email Work to Signup for Trestle?
  • Ruby Integrations: 403 Forbidden Errors
  • Getting 429: Too Many Requests Error – Why?
  • How to Remove or Deactivate a User in Trestle’s Developer Portal
  • How to Update Phone to Name/Address Linkage Records
  • Reviewing Usage Data
  • Why is the Name Associated with the Phone Incorrect?

Developer Portal

8
  • Business Verification Failed? Here’s What Documents You Need to Submit
  • How to Find and Download Your Receipt or Invoice
  • How to Monitor API Errors With Your Usage Graph
  • Batch Upload FAQ
  • Developer Portal Wallet Frequently Asked Questions
  • Export and Analyze Your Queries in Your Developer Portal Account
  • Getting Started with Trestle’s Developer Portal Wallet
  • Making Changes to Billing Settings for the Developer Portal Wallet

User Guides

9
  • Phone Validation in Java
  • Batch Upload Instructions
  • How Do I add Additional Members to My Trestle Account?
  • How to Handle Special Characters in API Queries
  • Phone Validation API with ASP.NET
  • Phone Validation with JavaScript and HTML: Leveraging Trestle’s API
  • Phone Validation API with PHP: Leveraging Trestle’s API
  • Phone Validation API with Python
  • Phone Validation API with React

Telephony Knowledge

9
  • Choosing the Right Number Lookup API
  • How to Identify Callers In Real-Time Using a Reverse Phone API
  • Why is Line Type Intelligence Important?
  • What is a “No Routes Found” Phone Message?
  • The Best Phone Validation API for Call Centers
  • How to Identify Disconnected Phone Numbers Automatically
  • What is a Phone Number Reputation Lookup?
  • What is a Carrier Number?
  • What is a Non-Fixed VoIP Phone?

Risk Suite Overview

8
  • How to Read Email Breach Reports and IP Abuse Reports in Decision Console
  • Everything to Know About Decision Signals API
  • How to Get Started With Decision Console
  • What is the Decision Overview and How Do I Read It?
  • What is an Attribute Card and How Do I Read It?
  • What is Link Builder and How Do I Use It?
  • Understanding Team and Account Management
  • FAQ and Troubleshooting: Decision Console
  • Home
  • Knowledge Base
  • User Guides
  • Phone Validation in Java
View Categories

Phone Validation in Java

6 min read

Ensuring the accuracy of user-provided phone numbers is a critical part of data collection. While Java offers a basic form of this validation, it falls short in many real-world validation metrics. Phone Validation API goes beyond a simple formatting check, offering a robust and reliable solution.

The Regex Approach in Java #

A common method for validating phone numbers in Java is to use a regular expression. This approach checks if the input string conforms to a predefined pattern for a phone number.

The following Java implementation validates a U.S. or Canadian phone number and includes a main method to demonstrate how to check both valid and invalid numbers:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class PhoneValidator {
    // Regex to match a 10 or 11-digit number, with an optional Leading '1' or '+1'
    private static final String PHONE_REGEX = "^(\\+?1)?[2-9]\\d{2}[2-9]\\d{2}\\d{4}$";
    private static final Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX); //

    public static boolean isValidPhoneNumber(String phoneNumber) {
        if (phoneNumber == null) {
            return false;
        }
        // Remove common formatting characters
        String cleanedNumber = phoneNumber.replaceAll("[\\s\\-()]", "");
        return PHONE_PATTERN.matcher(cleanedNumber).matches();
    }

    public static void main(String[] args) {
        String number = "1(206) 973-5100";

        // Check the valid number
        if (isValidPhoneNumber(number)) {
            System.out.println("Regex: The phone number '" + number + "' is valid.");
        } else {
            System.out.println("Regex: The phone number '" + number + "' is invalid.");
        }
    }
}

This code defines a regex pattern and a method to check if a given phone number string matches it after removing common formatting.

Rigid Formatting: The regex implementation above will only work correctly for U.S. and Canadian numbers. If you want to allow numbers outside of the United States or Canada, you will have to update this regex as follows:

    private static final String PHONE_REGEX = "^\\+?[1-9]\\d{6,14}$";

This updated implementation is more flexible but still has limitations. It can’t verify if a number is valid for a specific country. It also can’t verify what country a number is coming from without a large list of constants to parse.

If you want to allow maybe a couple of countries only, then something like this will work better:

private static final String PHONE_REGEX = "^((1)?[2-9]\\d{2}[2-9]\\d{2}\\d{4}|52\\d{10})$";

The above checks US, CA, and MX numbers. As you can see, the string is already getting fairly verbose with only three countries.

The Limitations of Regex #

While quick to implement, regex-based validation has significant drawbacks:

  • Format, Not Function: It can only verify that the number’s format is correct. It cannot determine if the number is actually in service assigned to a carrier and/or a subscriber.
  • No Real-World Data: Regex doesn’t provide valuable context like whether the number is a mobile, landline, or VoIP line.
  • Limited Scope: It can’t tell you if a number is active or has been recently disconnected.
  • No Vanity Number Support: It can’t take in numbers like 1-800-DIALME

A More Robust Solution: Trestle’s Phone Validation API #

Phone Validation API, on the other hand, offers a comprehensive and reliable validation process. By making a simple API call, you can get detailed, real-time information about a phone number.

Here’s how you can validate a phone number using Trestle’s API in Java. This example has been enhanced to parse key attributes from the JSON response and apply conditional logic:

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class TrestlePhoneValidator {
    private static final String API_KEY = "YOUR_API_KEY_HERE";
    private static final String BASE_URL = "https://api.trestleiq.com/3.0/phone_intel"; 

    public static void validatePhone(String phoneNumber) {
        HttpClient client = HttpClient.newHttpClient();
        try {
            // Properly encode the phone number
            String encodedPhone = URLEncoder.encode(phoneNumber, StandardCharsets.UTF_8);
            String fullUrl = BASE_URL + "?phone=" + encodedPhone;

            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(fullUrl))
                .header("x-api-key", API_KEY)
                .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            String responseBody = response.body();
            System.out.println("Response: " + responseBody);

            // Process the JSON response to check for validity and other details
            Boolean isValid = getJsonValue(responseBody, "is_valid", Boolean.class);
            Integer activityScore = getJsonValue(responseBody, "activity_score", Integer.class);

            if (isValid != null && !isValid) {
                 System.out.println("Result: This number is not valid.");
            } else if (activityScore != null && activityScore <= 30) {
                System.out.println("Result: This phone number is likely disconnected or inactive.");
            } else if (isValid != null && isValid) {
                 System.out.println("Result: Phone number is valid and active.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // A simple helper method to extract values from JSON string using regex.
    private static <T> T getJsonValue(String json, String key, Class<T> type) {
        Matcher matcher = Pattern.compile("\"" + key + "\":\\s*([^,}]+)").matcher(json);
        if (matcher.find()) {
            String valueStr = matcher.group(1).replace("\"", "");
            if (type == Boolean.class) {
                return type.cast(Boolean.valueOf(valueStr));
            }
            if (type == Integer.class) {
                return type.cast(Integer.valueOf(valueStr));
            }
        }
        return null;
    }
     public static void main(String[] args) {
        // Example with a potentially inactive number
        validatePhone("18005550199");
    }
}

This example uses Java’s built-in HttpClient to send a request to the Trestle API and retrieve validation results.

Comparison: #

FeatureJava RegexTrestle’s Phone Validation API
Basic Format ValidationYesYes
Verifies if Number is in ServiceNoYes
Identifies Line TypeNoYes
Provides Carrier InformationNoYes
Prepaid StatusNoYes
Activity ScoreNoYes
Real-time DataNoYes
Litigator ChecksNo Yes (add on)

The Trestle Advantage #

By integrating Phone Validation API, you gain a significant advantage over basic regex checks. The API not only confirms that a phone number is correctly formatted but also verifies its validity and provides valuable metadata. This includes the line type, carrier, and an activity score to gauge if the number is currently in use. This deeper level of insight allows businesses to reduce wasted outreach efforts and improve the quality of their contact data.

Updated on August 13, 2025
Phone Validation API with ReactBatch Upload Instructions
Table of Contents
  • The Regex Approach in Java
  • The Limitations of Regex
  • A More Robust Solution: Trestle's Phone Validation API
  • Comparison:
  • The Trestle Advantage
trestleLogo

Verified Identities. Trusted Interactions.

U.S. coverage for enrichment and verification.

Global coverage for phone validation and reverse phone.

Based in Bellevue, WA

Linkedin Github Postman

Company

  • About Us
  • Why Trestle
  • Careers
  • Affiliate Program
  • Contact

Products

  • Reverse Phone API
  • Reverse Address API
  • Caller Identification API
  • Phone Validation API
  • Real Contact API
  • Address Validation API
  • Batch Upload
  • Litigator Check Add-on
  • Free Lead Assessment

Use Cases

  • Outbound Dialing Optimization
  • Inbound Call Routing and Verification
  • Signup and Onboarding
  • Lead Verification
  • Optimize AI Voice Agents

Resources

  • Blog
  • Knowledge Base
  • Case Studies
  • Glossary
  • Data Dictionary
  • Changelog
  • Partners and Integrations

Developers

  • Developer Portal
  • API Documentation
  • API Live Status

Legal

  • Terms of Service
  • Privacy Policy
  • Data Processing Agreement
  • Service Level Agreement
  • Do Not Sell My Personal Information
Trestle - Identity Data Enrichment and Validation APIs
  • Products
        • Enrichment

        • Reverse Phone APIGLOBAL
        • Verify and enrich phone numbers
        • Reverse Address API
        • Verify and enrich address information
        • Caller Identification API
        • Identify and enrich caller information
        • Add-Ons

        • Litigator Check
        • Identify phone numbers associated with serial litigators
        • Email Deliverability
        • Confirm email inboxes accept mail in real-time
        • Spam Check
        • Flag phone numbers tied to high-risk calling activity
        • Email Age Score
        • Score how long an email has existed
        • Validation & Verification

        • Phone Validation APIGLOBAL
        • Validate phone numbers and identify disconnected numbers
        • Real Contact API
        • Verify phone, email, and address information
        • Address Validation API
        • Validate and normalize addresses
        • Assess Risk

        • Decision Console
        • Optimize identity verification for manual review
        • Decision Signals API
        • Automate identity verification for risk decisioning
        • Start using Trestle products today

          Get started for free—no credit card required

          Start Your Free Trial

  • Solutions
        • Industries

        • B2B Contact Data
        • eCommerce
        • Insurance
        • Lead Generation
        • Real Estate
        • Communications
        • Use Cases

        • Verify and Prioritize Leads
        • Outbound Dialing Optimization
        • Assess Risk And Prevent Fraud
        • Inbound Call Routing and Verification​
        • Signup and Onboarding​
        • Optimize AI Voice Agents
        • Start using Trestle products today

          Get started for free—no credit card required

          Start Your Free Trial

  • Pricing
  • Resources
        • API Documentation
        • Blog
        • Knowledge Base
        • Case Studies
        • Glossary
        • Partners and Integrations
  • Company
        • About Us
        • Why Trestle
        • Careers
        • Affiliate Program
        • Contact
  • Log In
  • Start for Free