Validando numeros internacionales usando jquery y regex
En el siguiente codigo tenemos dos funciones una de ellas se ejecuta cuando presionamos una tecla y la otra cuando salimos del input esta ultima llama una funcion para validar el contenido del campo
<input name="phone" id="phone">
<input name="phone" id="phone">
<script>
function validatePhone(txtPhone) {
var a = txtPhone;
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (fil.test(a)) {
console.log('true');
return true;
}
else {
console.log('false');
return false;
}
}
$("#phone").keydown(function (e) {
if($(this).val().length < 16 || e.keyCode == 8 || e.keyCode == 9){
// Allow: backspace, delete, tab, escape, enter
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110,107]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
//Allow ShiftKey and = when field is empty
(e.shiftKey && e.keyCode == 187 && !$(this).val()) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
} // Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}else{
e.preventDefault();
}
});
$("#phone").change(function (e){
if( validatePhone($("#phone").val()) ){
$("#phone").removeClass('glowing');
return;
}else{
$("#phone").addClass('glowing');
return false;
}
});
</script>
Comentarios
Publicar un comentario