jquery to validate phone number

后端 未结 9 1809
情话喂你
情话喂你 2020-12-01 06:34

I want to validate phone numbers like (123) 456-7890 or 1234567890 How should be the \'matches\' condition be written in the following code?

form.validate({         


        
9条回答
  •  情深已故
    2020-12-01 07:08

    I know this is an old post, but I thought I would share my solution to help others.

    This function will work if you want to valid 10 digits phone number "US number"

    function getValidNumber(value)
    {
        value = $.trim(value).replace(/\D/g, '');
    
        if (value.substring(0, 1) == '1') {
            value = value.substring(1);
        }
    
        if (value.length == 10) {
    
            return value;
        }
    
        return false;
    }
    

    Here how to use this method

    var num = getValidNumber('(123) 456-7890');
    if(num !== false){
         alert('The valid number is: ' + num);
    } else {
         alert('The number you passed is not a valid US phone number');
    }
    

提交回复
热议问题