jQuery(document).ready(function($) {
const phoneInput = $(‘#your-phone’);
const errorContainer = $(‘#phone-error’);
const submitButton = $(‘form.wpcf7-form input[type=”submit”]’);
let debounceTimer;
// Initialize intl-tel-input
phoneInput.intlTelInput({
preferredCountries: [“ae”, “us”, “gb”, “in”], // Add preferred countries
autoPlaceholder: “polite”,
allowDropdown: true,
nationalMode: false, // Always use international format
utilsScript: “https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.0/js/utils.js” // Load utils for formatting
});
// Initially disable the submit button
submitButton.prop(‘disabled’, true);
// Function to validate the phone number
function validatePhoneNumber() {
const fullPhoneNumber = phoneInput.intlTelInput(“getNumber”); // Get full number with country code
errorContainer.hide(); // Hide previous error messages
// Disable the submit button while validating
submitButton.prop(‘disabled’, true);
if (fullPhoneNumber) {
// AJAX request to the validation API
$.ajax({
url: ‘https://phonevalidation.abstractapi.com/v1/’,
type: ‘GET’,
data: {
api_key: ‘132e3c0b2d2748b1a228a68ffbfff06a’, // Your API key
phone: fullPhoneNumber // Use full phone number
},
success: function(response) {
console.log(response); // Log the valid response
if (!response.valid) {
errorContainer.text(‘Please enter a valid phone number.’).show();
} else {
console.log(‘Valid phone number:’, fullPhoneNumber);
// If valid, enable the submit button
errorContainer.hide(); // Hide any error messages
submitButton.prop(‘disabled’, false);
}
},
error: function() {
errorContainer.text(‘There was an error validating the phone number.’).show();
}
});
} else {
errorContainer.text(‘Phone number is required.’).show();
}
}
// Debounce function to limit the number of validation requests
function debounce(func, delay) {
return function() {
const context = this;
const args = arguments;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(context, args), delay);
};
}
// Event handler for input change to validate on typing
phoneInput.on(‘input’, debounce(function() {
validatePhoneNumber();
}, 500)); // Adjust delay as needed (500ms here)
// Event handler for when the input loses focus
phoneInput.on(‘blur’, function() {
validatePhoneNumber();
});
// Event handler for form submission
$(‘form.wpcf7-form’).on(‘submit’, function(event) {
if (submitButton.prop(‘disabled’)) {
event.preventDefault(); // Prevent submission if button is disabled
}
});
});