-3

Can someone help me with a regex expression for a phone number

it needs to be in this format only

xxx-xxx-xxxx

Timothy Wong
  • 95
  • 1
  • 1
  • 14

2 Answers2

1

Try this

^\d{3}\-\d{3}\-\d{4}$
Bacteria
  • 8,406
  • 10
  • 50
  • 67
0

Multiple ways are there. For example:

var regex = /^\d{3}-\d{3}-\d{4}$/;
console.log(regex.test('999-999-9999'));
console.log(regex.test('9999-999-99999'));

//OR
var regex2 = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/
console.log(regex2.test('999-999-9999'));
console.log(regex2.test('9999-999-99999'));

You can also write specific to a country or area. See this example.

If you are taking it from user input validate it like this:

var val = document.getElementbyId('yourInputId').value;
if(regex2.test(val)){
  alert("Success!!");
}
else{
  alert("Failure!!");
}
Community
  • 1
  • 1
Zee
  • 8,420
  • 5
  • 36
  • 58