Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

telephone number format with jquery&regex

i need to verify and convert any input val into telephone number format, i.e

input er+f375g25123435s67 i need to convert into +375 25 1234567

..

keyup: function(){
newval = $(this).val().replace(/(\D+|\+)/g, '');
newval = newval.replace(/\d(?=(?:\d{3})+(?!\d))/g, '$& ');
$(this).val(newval);
}

..

this is another code, i need to modify it..

like image 725
drdarwin Avatar asked Nov 27 '25 13:11

drdarwin


1 Answers

To strip out non-phone related characters:

var phone = "er+f375g25123435s67";
phone = phone.replace(/[^+|\d]/g, "");  // result = "+3752512343567"

Then to match phone pattern:

if (phone.match(/^[+][0-9]{12}$/)) // or /^[+][0-9]{13}$/ for 13 digits
    ...

EDIT: Here's what I was able to come up with for the test & replace:

phone = $(this).val().replace(/^[^+]{1}/, '');
if (phone.length > 1)
    phone = phone.substring(0,1) + phone.substring(1).replace(/[^\d]/g, '');
if (phone.match(/^[+][\d]{12}$/))
    phone = phone.substring(0,4) + " " + phone.substring(4,6) + " " + phone.substring(6,14);

Located here: http://jsfiddle.net/cabbott/KaYeJ/

like image 104
CAbbott Avatar answered Nov 29 '25 02:11

CAbbott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!