Skip to content

Commit e49b751

Browse files
committed
Complete telephone number algorithm
1 parent f16b7b2 commit e49b751

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

src/fcc-course-projects/fcc_course_projects.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ From the Freecodecamp Javascript Certification Algorithms Projects module
77
- [Palindrome Checker](#palindrome-checker)
88
- [Roman Numeral Converter](#roman-numeral-converter)
99
- [Caesars Cipher](#caesars-cipher)
10+
- [Telephone Number Validator](#telephone-number-validator)
1011

1112
#### Palindrome Checker
1213

@@ -79,3 +80,26 @@ export function rot13(str) {
7980
return decoded.join('');
8081
}
8182
```
83+
84+
#### Telephone Number Validator
85+
86+
Return `true` if the passed string looks like a valid US phone number.
87+
88+
The user may fill out the form field any way they choose as long as it has the format of a valid US number. The following are examples of valid formats for US numbers (refer to the tests below for other variants):
89+
90+
```text
91+
555-555-5555
92+
(555)555-5555
93+
(555) 555-5555
94+
555 555 5555
95+
5555555555
96+
1 555 555 5555
97+
```
98+
99+
For this challenge you will be presented with a string such as `800-692-7753` or `8oo-six427676;laskdjf`. Your job is to validate or reject the US phone number based on any combination of the formats provided above. The area code is required. If the country code is provided, you must confirm that the country code is 1. Return true if the string is a valid US phone number; otherwise return false.
100+
101+
```javascript
102+
export function telephoneCheck(str) {
103+
return /^(1 ?)?(\([0-9]{3}\)|[0-9]{3})[ \-]?[0-9]{3}[ \-]?[0-9]{4}$$/.test(str);
104+
}
105+
```
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export function telephoneCheck(str) {
2+
return /^(1 ?)?(\([0-9]{3}\)|[0-9]{3})[ \-]?[0-9]{3}[ \-]?[0-9]{4}$/.test(str);
3+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { telephoneCheck } from "../../src/fcc-course-projects/telephone_number";
2+
3+
test('should check telephone numbers', () => {
4+
expect(telephoneCheck("2323dfsf")).toBe(false);
5+
expect(telephoneCheck("5555555555")).toBe(true);
6+
expect(telephoneCheck("1 555-555-5555")).toBe(true);
7+
expect(telephoneCheck("555-555-5555")).toBe(true);
8+
expect(telephoneCheck("1 555)555-5555")).toBe(false);
9+
expect(telephoneCheck("(6054756961)")).toBe(false);
10+
});

0 commit comments

Comments
 (0)