0

I am fairly new to coding, especially Javascript, and am having difficulty getting my form to recognize phone numbers using parentheses. I have been able to make a code for accepting dashes between numbers to work, but the variations I have attempted with parentheses have all come back as invalid. Below is my functioning code with dashes. If possible, I was hoping to get some advice for how to adjust this code to incorporate parentheses. I am attempting to make the form function so that it can accept the following variations: xxx-xxx-xxxx , (xxx)xxxxxxx , and (xxx)xxx-xxxx.

function validateTenDigitsAndDashes (str)
{
    //alert("in validateTenDigitsAndDashes: str, str.length = '" + str + "', " + str.length) ;
    var retVal = 12 == str.length ;

    for (var i = 0 ; retVal && (i < str.length) ; i++) {
        //alert("   in loop: i, str.charAt(i) = " + i + ", " + str.charAt(i)) ;
        if (3 == i || 7 == i) retVal = '-' ==  str.charAt(i)
        else                  retVal = isDigit(str.charAt(i)) ;
        }

    return retVal ;
}
Touheed Khan
  • 2,149
  • 16
  • 26
Holly
  • 3
  • 3

2 Answers2

0

Hope it may help you.

function telephoneCheck(str) {
  var a = /^(1\s|1|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/.test(str);
  alert(a);
}

//call function to check
telephoneCheck("(555) 555-5555");

Answer picked from below link on stackoverflow.

Validating Phone Numbers Using Javascript

Abhishek
  • 1,543
  • 3
  • 13
  • 29
  • 2
    There is no point in duplicating content on the website. Rather you have enough rep to flag the question as duplicate of the original question. – Nisarg Shah Feb 26 '18 at 06:11
0

A small regex like this would do the trick ^\(?\d{3}\)?-?\d{3}-?\d{4}$

Adarsh
  • 827
  • 9
  • 23