As said before, you can first modify your entire
String before validating. For instance:
After the loop all whitespace characters, -, ( and ) are removed. All letters from A-Z (both upper and lower) are converted to numbers.
Of course regular expressions are also possible, but the regex would be quite hard to accommodate all formats you want to allow; xxx-xxx-xxxx, (xxx)xxx-xxxx, xxx xxx xxxx, (xxx) xxx xxxx, xxxxxxxxxx, etc.
Come to think of it, if those are the only formats then it's actually not that hard:
- (xxx) or xxx; a closing bracket should only be allowed if there is an opening bracket
- whitespace, dash or nothing
- xxx
- whitespace, dash or nothing
- xxxx
Of course that regex would have to be applied after the letter-to-number mapping to allow 800-555-SUN1.