Near the end of my project and I require some assistant.I need a regex code to validate the phone number. If the phone number is not empty, validate that the phone number is in one of the following formats:
‘xxx–xxx-xxxx’ – 10 digits with two dashes where the first dash is between the third and fourth digits and the second dash is between the sixth and seventh digits.
‘xxxxxxxxxx’’ – all 10 digits, or,
‘(xxx)xxxxxxx’’ – 10 digits with the first three digits being enclosed by parentheses.
‘(xxx)–xxx-xxxx’ – 10 digits with the first three digits being enclosed by parentheses, and there is a dash between the sixth and seventh digits. Also it needs to provide an alert if the phone number is not in the required format. All formats must be accepted by the validation or else it fails.
My issue is that I made an attempt to do this with regular expression because I feel that this is easy for me. I’m not an experience programmer at all so write codes have never been my thing and my question is there a RegExpression that covers all the formats at once and still able to give me an alert if no number is selected and the user not using one of the required formats.
Here is my current code but it does not cover the four formats.
var phone = document.myForm.phone.value;
if (!/^\d{3}-\d{3}-\d{4}$/.test(document.myForm.phone.value)) {
alert("Please enter the correct phone format ");
This code only covers xxx-xxx-xxxx. Is it possible to cover all formats with this kind of code? Please it must be regex starting with “var phone” like I have in my code example or it tends to get messy.
Thanks in advance