@Christonja/

Telephone Number Validator

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*JavaScript Algorithms and Data Structures Projects: Telephone Number Validator:
Challenge designed by FreeCodeCamp, solution derived from learning obtained thanks to FreeCodeCamp and with some assistance from other people's solutions on the internet. I'm not willing to take ownership of the below code beyond that I was on the right track. ie. completely my solution however forgot about the ? syntax as an option and therefore followed someone elses example to implement this into my solution. Once I figured out how it worked for the first part of the regular expression I debugged the remainder myself and implemented the ? regex syntax without following any examples. 
Function calls provided by FreeCodeCamp as ways to test the algorithm*/

function telephoneCheck(str) {
  var r1 = /^(1\s?)?(\d{3}-\d{3}-\d{4}$|[(]\d{3}[)](\s?)\d{3}-\d{4}$|^[(]\d{3}[)] \d{3}-\d{4}$|^\d{3} \d{3} \d{4}$|^\d{10}$|^\d{1} \d{3} \d{3} \d{4}$)/;

  console.log(str + ": "+ r1.test(str));
  if (r1.test(str)) {
    return true;
  } else {
    return false;
  }
}

telephoneCheck("555-555-5555") //should return a boolean.
telephoneCheck("1 555-555-5555") //should return true.
telephoneCheck("1 (555) 555-5555") //should return true.
telephoneCheck("5555555555") //should return true.
telephoneCheck("555-555-5555") //should return true.
telephoneCheck("(555)555-5555") //should return true.
telephoneCheck("1(555)555-5555") //should return true.
telephoneCheck("555-5555") //should return false.
telephoneCheck("5555555") //should return false.
telephoneCheck("1 555)555-5555") //should return false.
telephoneCheck("1 555 555 5555") //should return true.
telephoneCheck("1 456 789 4444") //should return true.
telephoneCheck("123**&!!asdf#") //should return false.
telephoneCheck("55555555") //should return false.
telephoneCheck("(6054756961)") //should return false
telephoneCheck("2 (757) 622-7382") //should return false.
telephoneCheck("0 (757) 622-7382") //should return false.
telephoneCheck("-1 (757) 622-7382") //should return false
telephoneCheck("2 757 622-7382") //should return false.
telephoneCheck("10 (757) 622-7382") //should return false.
telephoneCheck("27576227382") //should return false.
telephoneCheck("(275)76227382") //should return false.
telephoneCheck("2(757)6227382") //should return false.
telephoneCheck("2(757)622-7382") //should return false.
telephoneCheck("555)-555-5555") //should return false.
telephoneCheck("(555-555-5555") //should return false.
telephoneCheck("(555)5(55?)-5555") //should return false.
Native Browser JavaScript