0

Does anyone know how to wring a simple US format phone number checker without using the validation plugin?

So far I have something like this, but I can't seem to get it to work.

if($(this).hasClass('phoneNum')) {
    var phone_number = $(this.value).replace(/\s+/g, ''); 
    if(phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)) {
        //..........do stuff
    }
}
2

2 Answers 2

1

I think your issue is:

var phone_number = $(this.value).replace(/\s+/g, '');

Should be:

var phone_number = $(this).val().replace(/\s+/g, '');

There may be another issue, but this jumps out to me immediately.

0

MadTurki you were right but j08691 thank you for directing me to a post that answers this question better. I ended up going with the following and it works great!

if($(this).hasClass('phoneNum')){
            var error = 1;
            var hasError = false;
            var $this = $(this);
            var regex1 = /^([2-9]{1}\d{2})([2-9]{1}\d{2})\d{4}$/;
            phone = $(this).val();
            phone = phone.replace(/[^0-9]/g,'');        
            if(!regex1.test(phone)){
                isValid = false;
                $this.css('background-color','#FF7575');
            }   
            else{
                area = phone.substring(0,3);
                prefix = phone.substring(3,6);
                line = phone.substring(6);
                $this.val('(' + area + ') ' + prefix + '-' + line);
                $this.css('background-color','#A7E9A7');    
            }
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.