Validate US phone number using jQuery validation

Posted By : Shiv Kumar | 09-Jul-2014

I had a requirement to validate US phone number in (ddd)ddd-dddd format using jQuery.

I have solved this problem by using jQuery validation plugin :

$("#myform").validate({
rules: {
field: {
required: true,
phoneUS: true
}
}
});

Files required for this :

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>

It sometimes doesn't work.

To get it working we have to include Jquery addtional-methods.min.js

If still it doesn't work then you have to use following script before validate method which contains regex to validate :

jQuery.validator.addMethod("phoneUS", function (phone_number, element) {
            phone_number = phone_number.replace(/\s+/g, "");
            return this.optional(element) || phone_number.length > 9 &&
                  phone_number.match(/\(?[\d\s]{3}\)[\d\s]{3}-[\d\s]{4}$/);
        }, "Invalid phone number");

It finally solve the problem. If you have required some other format then modify above regex according to need.

Thanks

Shiv Kumar

About Author

Author Image
Shiv Kumar

Shiv is an experienced Java Developer with a strong background in multiple technologies. He specializes in defining system architectures to ensure reliable and resilient solutions. He possesses a comprehensive understanding of the latest technologies and has hands-on experience in Core Java, Spring Boot, Hibernate, Apache Kafka messaging queue, Redis, as well as relational databases like MySQL and PostgreSQL, and non-relational databases like MongoDB. He excels in API implementations, Microservices, Web Services development, testing, and deployments. Shiv actively contributes to code enhancements and consistently delivers valuable contributions to various client projects, including Fabtrack, Pando, Pandojo, Digikam, WhatsApp Integration, Croniz, Punchin Application, Script TV, Bhaasha, and more. He demonstrates strong analytical skills and a creative mindset. In addition, he has a passion for reading books and exploring new technologies and innovations.

Request for Proposal

Name is required

Comment is required

Sending message..