js telephone number validation code example

Example: telephone number validator javascript

// Valid US Phone Number but can be tweaked.

const telephoneCheck = str => {
  const regExp = /^1?\s?(\(\d{3}\)|\d{3})(\s|-)?\d{3}(\s|-)?\d{4}$/gm
  return regExp.test(str)
}

telephoneCheck("27576227382");

			/*			Regular Expression Explanation Below !!! 			*/

/*
	Expression : /^1?\s?(\(\d{3}\)|\d{3})(\s|-)?\d{3}(\s|-)?\d{4}$/gm
    
    ^ asserts position at start of a line
    1? matches the character 1 literally (case sensitive)
    ? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
    \s? matches any whitespace character (equal to [\r\n\t\f\v \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff])
    ? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
    1st Capturing Group (\(\d{3}\)|\d{3})
    1st Alternative \(\d{3}\)
    \( matches the character ( literally (case sensitive)
    \d{3} matches a digit (equal to [0-9])
    {3} Quantifier — Matches exactly 3 times
    \) matches the character ) literally (case sensitive)
    2nd Alternative \d{3}
    \d{3} matches a digit (equal to [0-9])
    {3} Quantifier — Matches exactly 3 times
    2nd Capturing Group (\s|-)?
    ? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
    1st Alternative \s
    \s matches any whitespace character (equal to [\r\n\t\f\v \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff])
    2nd Alternative -
    - matches the character - literally (case sensitive)
    \d{3} matches a digit (equal to [0-9])
    {3} Quantifier — Matches exactly 3 times
    3rd Capturing Group (\s|-)?
    ? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)
    1st Alternative \s
    \s matches any whitespace character (equal to [\r\n\t\f\v \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff])
    2nd Alternative -
    \d{4} matches a digit (equal to [0-9])
    {4} Quantifier — Matches exactly 4 times
    $ asserts position at the end of a line
    Global pattern flags
    g modifier: global. All matches (don't return after first match)
    m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
*/

// With love @kouqhar