User
User

Reputation: 1662

Phone number validation in jquery

I use the following function to validate the a phone number textbox. It works fine. This function allow to enter only digits, but if I Enter the text box, the entries look like 1111111. But I need the entries look like 111-111-1111 111111.

How can I do this?

$('input[id*=Phone]').live('keypress',function(evt){
    var phValidateid=$(this).attr("id");
    if (event.keyCode > 47 && event.keyCode < 58) {
        return true;
    }
    return false;
});

Upvotes: 0

Views: 4807

Answers (2)

Ram
Ram

Reputation: 144729

you can try something like this:

$('input').on('keyup',function(evt){
    var len = this.value.length;
    if (len == 3 || len == 7 || len == 11) {
       $(this).val(this.value + "-");
    }

    else if (len == 15) {
      $(this).val(this.value + " ");  
    }           
});

http://jsfiddle.net/Ys79C/2/

Upvotes: 4

i100
i100

Reputation: 4666

try

return String.fromCharCode(event.keyCode).search(/[\d\-]/) > -1; // true if number or dash; false otherwise

or if you'd like to check the hole value of the input

$('input[id*=Phone]').live('keypress',function(evt){
    return $(this).val().search(/^\d{3}\-\d{3}\-\d{4} \d{6}$/) > -1;
});

Upvotes: 0

Related Questions