0

Possible Duplicate:
A comprehensive regex for phone number validation

Perhaps a forgiving JavaScript solution would only make sure that only valid characters are allowed. (digits, dashes, periods, letters for extension.

Although loop seems best, is there a simple regular expression that checks for valid characters?

Community
  • 1
  • 1
finneycanhelp
  • 9,018
  • 12
  • 53
  • 77
  • http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation/123666#123666 – sidyll Jun 01 '11 at 12:40

2 Answers2

1

Your regex: \d|\.|\-

Although technically you want the opposite [^\d\.\-] so you can do a replace ->

$('input').blur(function() {

   var value = $(this).val();
   $(this).val(value.replace(/[^\d\.\-]/g, ''));

});

See fiddle in action - http://jsfiddle.net/GspT4/

John Strickler
  • 25,151
  • 4
  • 52
  • 68
0

A regular expression is just javascript, not jQuery. What is the format you seek? How many letters are allowed in the extension? I could look it up, but it would help greatly if you would do that. It seems numbers from 7 to 11 digits are allowed.

It is nice to allow users to enter phone numbers in block of 3 or 4 characters because it is much easier for them to read, like:

914-499-1900

or

914 499 1900

or similar. Trim the spaces for validation or storage if you like.

For the above formats exactly:

function testPhoneNumber(phoneNumber) {
  var re = /^\d{3}[- ]?\d{3}[- ]?\d{4}$/;
  return re.test(phoneNumber);
}

Or you can remove unnecessary but allowed characters and test what remains:

function testPhoneNumber(phoneNumber) {
  var re = /^\d{10}$/;
  return re.test(phoneNumber.replace(/[ -+]/g,''));
}

But these don't allow for extension. If you provide the format, the regular expression part is easy.

RobG
  • 142,382
  • 31
  • 172
  • 209