user627074
user627074

Reputation: 1

phone number validation in javascript

I need a phone validation code that accept only digits and dashes like this format 777-777-7777 , length is equal to 12. I'm new to Jquery and I really appreciate your help.

here my code:

var x=document.forms["myForm"]["phone"].value
if (x==null || x=="")
  {
  alert("Business phone number must be filled out");
      return false;
  }

Thanks!

Upvotes: 0

Views: 173

Answers (1)

mVChr
mVChr

Reputation: 50215

You can use a simple RegExp to test 3digits-dash-3digits-dash-4digits as follows:

var phoneTest = new RegExp("\\d{3}-\\d{3}-\\d{4}"),
    phoneNum = "777-777-7777",
    otherNum = "66-666-6666";

phoneTest.test(phoneNum); // returns true
phoneTest.test(otherNum); // returns false

Upvotes: 1

Related Questions