Here is my problem:
Create a constructor for a telephone number given a string in the form xxx-xxx-xxxx or xxx-xxxx for a local number. Throw an exception if the for
So I was thinking to validate it using a regular expression, but I don't know if I'm doing it correctly.
It indeed looks overcomplicated. Also, matching xxx-xxx-xxxx
or xxx-xxxx
where x
is a digit can be done better with "(\\d{3}-){1,2}\\d{4}"
. To learn more about regex I recommend to go through http://regular-expressions.info.
Also what kind of exception would I have to throw? Do I need to create my own exception?
A ValidatorException
seems straight forward.
public static void isPhoneNumberValid(String phoneNumber) throws ValidatorException {
if (!phoneNumber.matches(regex)) {
throws ValidatorException("Invalid phone number");
}
}
If you don't want to create one yourself for some reasons, then I'd probably pick IllegalArgumentException
, but still, I don't recommend that.
That said, this validation of course doesn't cover international and/or external telephone numbers. Unless this is really homework, I'd suggest to rethink the validation.