Search code examples
javascriptjqueryvalidationphone-number

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;
});

Solution

  • 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/