I needed a generic validator for a phone number, and I started thinking about the format of the number but at the end of the day I just want to be sure that there are 10 digits in the entry, and the user can decorate that however he or she like with brackets, hyphens, dots and spaces, but as long as there are 10 digits in the mix and there aren’t any clearly invalid characters like letters or weird punctuation, I’m good.
So: a regex to make sure that a string contains at least 10 digits along with any optional spaces, dashes, brackets and dots:
1: Regex tester = new Regex(@"^([-() ]*\d[-() .]*){10}$");
2:
3: Assert.IsTrue(tester.IsMatch("123-456-7890"));
4: Assert.IsTrue(tester.IsMatch("123 456 7890"));
5: Assert.IsTrue(tester.IsMatch("1234567890"));
6: Assert.IsTrue(tester.IsMatch("(123) 456-7890"));
7: Assert.IsTrue(tester.IsMatch("123.456.7890"));
8: Assert.IsTrue(tester.IsMatch("123 4567890"));
9:
10: Assert.IsFalse(tester.IsMatch(""));
11: Assert.IsFalse(tester.IsMatch("123"));
12: Assert.IsFalse(tester.IsMatch("werew"));
13: Assert.IsFalse(tester.IsMatch("12345678901"));
14: Assert.IsFalse(tester.IsMatch("123x567890"));
15: Assert.IsFalse(tester.IsMatch("123-456-7890 x32"));
16: Assert.IsFalse(tester.IsMatch("123-456-7890x"));
It’s up to the application to filter and reformat the entry for internal storage. I like just storing the digits so later applications can reformat as needed, so I go with something like this:
1: string enteredNumber = "(123) 456-7890";
2: string justDigits =
3: new Regex(@"[^\d]").Replace(enteredNumber, "");
4: Assert.AreEqual("1234567890", justDigits);
Leave a Reply