Quick Update: If you’re landing on this thread looking for a way to limit phone number characters, you no longer need to use custom scripts or workarounds!
The phone input fields now include an international country code dropdown. Once a customer selects their country, the form automatically verifies the correct character length and format for that specific region. It’s completely built-in, meaning it prevents typos and invalid numbers automatically without any extra setup or coding on your end.
It might be possible with some Javascript, but I do not think it’s necessary, as we are working on a solution to make sure Phone numbers are valid before submitting the order. It might take sometime to be rolled out but will be worth the wait.
I have the code to make this work, I used to validate phone numbers from Colombia.
<script>
document.addEventListener('DOMContentLoaded', function () {
var submitButton = document.getElementById('submitButton');
// Agregar el evento en la fase de captura
submitButton.addEventListener('click', function(event) {
var inputTelefono = document.getElementsByName('phone')[0];
var telefono = inputTelefono.value;
var patronTelefonoColombia = /^3\d{9}$/;
if (!patronTelefonoColombia.test(telefono)) {
alert('Por favor ingrese un número de teléfono válido en Colombia (10 dígitos y comienza con 3).');
event.stopImmediatePropagation(); // Detiene la propagación del evento
}
}, true); // True indica que el evento se maneja en la fase de captura
});
</script>
The only thing you have to set up the id of the submit button to ‘submitButton’.
If you have any doubts, don’t hesitate to contact me.
Muchas gracias por el código. ¿Podrías agregar también que verifique la cantidad de dígitos? Es decir, si el comprador escribe menos de 10 digitos muestre el mensaje de alerta. También sería muy bueno que solo permita ingresar números y bloquee el resto de carácteres.
Muchas gracias.
<script>
document.addEventListener('DOMContentLoaded', function () {
var inputTelefono = document.getElementsByName('phone')[0];
var submitButton = document.getElementById('submitButton');
// Validar la entrada para permitir solo números
inputTelefono.addEventListener('input', function() {
this.value = this.value.replace(/\D/g, '');
});
// Agregar el evento en la fase de captura
submitButton.addEventListener('click', function(event) {
var telefono = inputTelefono.value;
var patronTelefonoColombia = /^3\d{9}$/;
if (telefono.length < 10) {
alert('Por favor ingrese al menos 10 dígitos.');
event.stopImmediatePropagation(); // Detiene la propagación del evento
return;
}
if (!patronTelefonoColombia.test(telefono)) {
alert('Por favor ingrese un número de teléfono válido en Colombia (10 dígitos y comienza con 3).');
event.stopImmediatePropagation(); // Detiene la propagación del evento
}
}, true); // True indica que el evento se maneja en la fase de captura
});
</script>