r/dailyprogrammer • u/rya11111 3 1 • Feb 18 '12
[2/18/2012] Challenge #10 [easy]
The exercise today asks you to validate a telephone number, as if written on an input form. Telephone numbers can be written as ten digits, or with dashes, spaces, or dots between the three segments, or with the area code parenthesized; both the area code and any white space between segments are optional.
Thus, all of the following are valid telephone numbers: 1234567890, 123-456-7890, 123.456.7890, (123)456-7890, (123) 456-7890 (note the white space following the area code), and 456-7890.
The following are not valid telephone numbers: 123-45-6789, 123:4567890, and 123/456-7890.
source: programmingpraxis.com
1
u/pheonixblade9 Mar 14 '12
Java in 5 lines (with explanation). Should work with international phone numbers, as well.:
I wrote a short blog post with a bunch of data validation methods. :)
2
u/JerMenKoO 0 0 Feb 18 '12
Asking for hint, is using regex a good idea?
2
u/[deleted] Feb 18 '12
Node.js :
2
u/[deleted] Feb 18 '12 edited Feb 18 '12
Javascript
EDIT: forgot the dashes in the regex for the second match
1
u/wsppan Feb 18 '12
easiest thing to do is strip out non numeric characters and vaildate the number of digits is 10.
1
u/[deleted] Feb 18 '12
1
u/aagavin Feb 18 '12
Javascript:
1
u/jnaranjo Feb 19 '12
Python2.7 solution - complete with a test function.
http://pastebin.com/3A66zAS8
1
u/Tyaedalis Feb 19 '12
Python 2.7.2 command line:
http://pastebin.com/Ndhapepn
1
u/cooper6581 Feb 19 '12
Python. I tried to come up with 1 RegEx to rule them all, but still have some problems. This was the closest I got.
Results:
1
u/[deleted] Feb 19 '12
Whoo! My first python program!
1
u/Yuushi Mar 19 '12
Getting the regex correct for this is actually more difficult than it first appears, especially with mismatched (. In fact, you need to break it into two cases, either starting with a '(' or not. Regex isn't capable of parens matching, so making sure '(123-456-7890' fails is important.
Python:
Some test cases:
1
u/ragtag_creature Dec 12 '22
R
0
u/[deleted] Feb 18 '12
[deleted] — view deleted comment
0
u/[deleted] Feb 18 '12
[deleted] — view deleted comment