Reputation: 901
i am trying to do some validation on a phone number although i understand how to do validation for just numbers of a set size this task is a little tricky
i am required to have validation on a users phone number however it must be in any one of the formats illustrated below (where spaces are not significant):
+44 (23) 92846438
(023) 92846438
how would i create a custom validation that would validate against all combinations of the above phone numbers ?
Thanks
i have tried created a backing bean and validating through that
public class PhoneValidator implements Validator{
private static final String phone_PATTERN = "^[0-9-]{12,15}$";
private Pattern pattern;
private Matcher matcher;
public UserNameValidator(){
pattern = Pattern.compile(phone_PATTERN);
}
@Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
matcher = pattern.matcher(value.toString());
if(!matcher.matches()){
FacesMessage msg =
new FacesMessage("Phone validation failed",
"Invalid phone number.");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}
would something like this work :
private static final String phone_PATTERN = "^[+][44][(0-9)][0-9-]{12,15}$";
and if so how can i get it to check both methods
edit, i have tried the above but it does not work, i think i am on the right lines here just can not get the combination right
Upvotes: 0
Views: 5042
Reputation: 564
^(\\+\\d\\d )?\\(\\d{2,3}\\) \\d{8}$
The above matches both of those examples. Test out regex real quick and easy @ regexpal.com
{X} means the preceding pattern chunk must occur X times, {X,Y} also works if you're flexible
also consider using "|" (pipe character) which stands for "or". Ex: in X|Y It will grab matches of X or Y.
Upvotes: 1
Reputation: 901
managed to find the regular expression needed
incase anyone needs it it is here, it will work on any u.k. number
private static final String Phone_PATTERN = "^\\(?(?:(?:0(?:0|11)\\)?[\\s-]?\\(?|\\+)44\\)?[\\s-]?\\(?(?:0\\)?[\\s-]?\\(?)?|0)(?:\\d{2}\\)?[\\s-]?\\d{4}[\\s-]?\\d{4}|\\d{3}\\)?[\\s-]?\\d{3}[\\s-]?\\d{3,4}|\\d{4}\\)?[\\s-]?(?:\\d{5}|\\d{3}[\\s-]?\\d{3})|\\d{5}\\)?[\\s-]?\\d{4,5}|8(?:00[\\s-]?11[\\s-]?11|45[\\s-]?46[\\s-]?4\\d))(?:(?:[\\s-]?(?:x|ext\\.?\\s?|\\#)\\d+)?)$";
Upvotes: 0