drdarwin
drdarwin

Reputation: 107

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..

Upvotes: 3

Views: 1249

Answers (3)

Yuri Ghensev
Yuri Ghensev

Reputation: 2545

$('input').live({   
    keyup: function() {           
        var ipt = $(this).val().replace(/[^\d]*/g, ""); // remove non-digits

        ipt = ipt.replace(/(\d{1,3})(\d{1,2})?(\d{1,7})?.*/g, '+$1 $2 $3');

        $(this).val(ipt);       
    }
});

Fiddle to test

Upvotes: 2

CAbbott
CAbbott

Reputation: 8098

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/

Upvotes: 2

Khan
Khan

Reputation: 516

You can try this :

// this removes non numeric

keyup: function(){

var phone = $(this).val().replace(/\D/g, '');
var myRegexp = /(\d{3})(\d{3})(\d*)/g

var match = myRegexp.exec(phone); $(this).val('+' + match [1] + ' ' + match [2] + ' ' + match [3]);

}

$1 $2 and $3 should be 375 25 1234567

Comment : sorry didn't know you wanted a full answer with the code. http://jsfiddle.net/UcJeV/4/

Upvotes: 2

Related Questions