Phone validation in JavaScript and HTML lets you check a phone number’s format at the point of entry, before it reaches your server. Using an HTML tel input with a pattern attribute plus a JavaScript function, you can give users real-time feedback. For deeper checks like whether a number is active or disconnected, pair this client-side check with Phone Validation API.
When building web applications that collect phone numbers, one of the most fundamental tasks is to validate that the input matches the expected format of a phone number in a given country. For instance, a basic check to verify if the phone number contains 10 or 11 digits and only includes specific characters is an easy way to ensure the provided number is potentially valid. Without this initial verification, businesses risk wasting time and resources pursuing leads or reaching out to individuals with inaccurate data.
While there are various tools available for phone number validation, implementing a solution using JavaScript and HTML provides valuable insights into the potential legitimacy of the data you’re collecting, right at the point of entry. This approach is cost-effective and relatively straightforward to implement, making it an excellent first line of defense in your data validation strategy.
It’s worth noting that JavaScript and HTML validation isn’t limited to phone numbers. This versatile approach can be applied to a wide range of standardized text inputs, such as email addresses, postal codes, and more. However, for this guide, we’ll focus specifically on phone number validation for the U.S. and Canadian markets, which is Trestle’s area of expertise.
What is JavaScript and HTML Validation? #
JavaScript and HTML validation is a client-side approach to ensuring that user input meets specific criteria before it’s submitted to the server. In the context of phone numbers, it allows you to check if the entered number matches the expected format for U.S. or Canadian phone numbers.
HTML5 introduced the pattern attribute for input fields, which allows you to specify a regular expression (regex) that the input must match. When combined with JavaScript, you can provide real-time feedback to users and prevent submission of invalid data.
Implementing Phone Number Validation with JavaScript and HTML #
Let’s look at a complete Javascript phone number validation example built around a simple HTML phone validation form:
<form id="phoneForm">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone"
pattern="^\+?1?\d{10}$"
required>
<span id="phoneError" style="color: red;"></span>
<button type="submit">Submit</button>
</form>
<script>
function validatePhone(phone) {
// Remove all non-digit characters
var digits = phone.replace(/\D/g, '');
if (digits.length === 11 && digits[0] !== '1') {
return "For 11-digit numbers, please ensure it starts with '1' for US/Canada.";
}
if (digits.length !== 10 && digits.length !== 11) {
return "Please enter a 10-digit phone number, or 11 digits including the country code '1'.";
}
if (digits.length === 11 && digits[0] === '1') {
digits = digits.slice(1); // Remove the leading 1
}
if (digits[0] === '0' || digits[0] === '1') {
return "The area code should start with a digit between 2 and 9.";
}
return ""; // Empty string means no errors
}
document.getElementById('phone').addEventListener('input', function() {
var error = validatePhone(this.value);
document.getElementById('phoneError').textContent = error;
});
document.getElementById('phoneForm').addEventListener('submit', function(e) {
var phone = document.getElementById('phone').value;
var error = validatePhone(phone);
if (error) {
document.getElementById('phoneError').textContent = error;
e.preventDefault();
} else {
// Form is valid, you can submit it or perform additional actions
console.log('Phone number is valid:', phone);
}
});
</script>
This code provides real-time feedback as the user types and also prevents form submission if the phone number is invalid.
Pros and Cons of JavaScript and HTML Validation #
Pros: #
- Immediate feedback to users
- Reduces server load by catching errors client-side
- Improves user experience
- Can prevent submission of obviously invalid data
Cons: #
- Can be bypassed by savvy users
- Limited to format checking, can’t verify if the number is actually in service
- May not catch all possible valid formats, especially for international numbers
- Requires JavaScript to be enabled in the browser
Introducing Trestle’s Phone Validation API #
While client-side validation is useful, it has limitations. This is where Trestle’s Phone Validation API comes in. Our API provides a more comprehensive validation solution that goes beyond simple format checking.
The Advantage of Combining JavaScript and HTML Validation with Trestle’s Phone Validation API #
When you supplement client-side validation with APIs like Trestle’s Phone Validation API, you can be more confident that you are working with potentially valid phone numbers. The response from the API can tell you if a number is not only correctly formatted, but also if it’s valid, active, and valuable to your business.
Here’s how you might combine JavaScript validation with a call to Trestle’s API:
document.getElementById('phoneForm').addEventListener('submit', function(e) {
e.preventDefault();
var phone = document.getElementById('phone').value;
if (!phone.match(/^\+?1?\d{10}$/)) {
document.getElementById('phoneError').textContent = 'Please enter a valid US or Canadian phone number.';
return;
}
// If client-side validation passes, call Trestle's API
fetch(`https://api.trestleiq.com/3.0/phone_intel?phone=${phone}`, {
headers: {
'x-api-key': 'YOUR_API_KEY_HERE'
}
})
.then(response => response.json())
.then(data => {
if (data.is_valid) {
console.log('Phone number is valid!');
console.log('Carrier:', data.carrier);
console.log('Line type:', data.line_type);
console.log('Activity score:', data.activity_score);
// Process the valid phone number
} else {
document.getElementById('phoneError').textContent = 'This number appears to be invalid or disconnected.';
}
})
.catch(error => {
console.error('Error:', error);
});
});
Note: Replace YOUR_API_KEY_HERE with the key from your Developer Portal account.
For production, avoid exposing your API key in client-side JavaScript, since anything in the browser is visible to users. Route the API call through your own backend, keep the key in a server-side environment variable, and return only the result to the browser.
Key Benefits of Trestle’s Phone Validation API #
- Syntax Check: Confirms the number follows the correct format for US/Canada numbers.
- Validity Check: Verifies if the number is assigned to a carrier.
- Activity Status: Determines if the number is connected or disconnected as well as associated activity.
By leveraging Trestle’s Phone Validation API, you can filter out bad leads and sign ups more effectively and prioritize the good ones, going beyond what client-side validation alone can offer.
Wrapping Up #
Combining client-side validation with Trestle’s Phone Validation API provides a robust solution for ensuring the quality and accuracy of phone number data. While JavaScript and HTML validation offer immediate feedback and improve user experience, Trestle’s API adds an extra layer of verification that can significantly enhance your lead quality and customer data management.
Ready to take your phone number validation to the next level? Sign up for a free Trestle account and start leveraging our powerful Phone Validation API today!
If you have any questions or need assistance with integration, our team is here to help. Contact us to learn how we can support your specific needs. Visit our API documentation to learn more.
This blog post was written by Tyler Woodward, Technical Account Manager at Trestle.
Frequently Asked Questions #
How do I validate a phone number in JavaScript?
Use an HTML tel input with a pattern attribute for the basic format rule, then add a JavaScript function that strips non-digit characters and checks the length and area code. The example above is a complete, copy-pasteable implementation you can drop into your form.
Can JavaScript confirm whether a phone number is real or active?
No. Client-side validation only confirms that a number is formatted correctly. It cannot tell you whether the number is assigned to a carrier or currently in service. To confirm validity and activity, send the number to Trestle’s Phone Validation API, which returns the carrier, line type, and an activity score.
How do I call Phone Validation API from JavaScript?
Send a GET request to the phone_intel endpoint with the phone number as a query parameter and your API key in the x-api-key header, using fetch. The JSON response includes is_valid, line_type, carrier, and activity_score. See the API documentation for the full response structure.
Is it safe to put my API key in client-side JavaScript?
No. Anything in client-side code is visible to end users. For production, make the Trestle API call from your own server, store the key in an environment variable, and pass only the result back to the browser.