JS Phone Validator - A Better Solution IMO

So I took a look at Solution 1 that FCC posted for this project in the Javascript certification. Here’s the FCC regex:

var regex = /^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\s\-]?\d{4}$/;

While it technically passes all the tests required by the project, it also has some funky formats that return true. IMO the following formats should be invalid:

  • (123)-456 7890
  • 123 456-7890
  • 123-456 7890

Furthermore, (123) 456 7890 should be a valid format. I know the FCC solution is right because it doesn’t require these formats… but these other cases were bugging me. Hence, I think a better solution to this problem would be:

    let rex1 = /^(1\s?)?\d{3}([-\s]?)\d{3}\2\d{4}$/,
        rex2 = /^(1\s?)?\(\d{3}\)\s?\d{3}[-\s]?\d{4}$/;

    if (rex1.test(str)) {
        return true;
    }
    else {
        return rex2.test(str) ? true : false
    }
}

So basically the problem has to be solved with 2 regular expressions if you want to validate these additional formats. I don’t think there is a way to solve this with just one regex… is there? Can you think of an even better way to solve this problem?

Thanks!

20 Likes