-
Notifications
You must be signed in to change notification settings - Fork 7
/
PhoneNumberValidator.java
68 lines (58 loc) · 2.18 KB
/
PhoneNumberValidator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.biz.tenants;
import sirius.db.mixing.Property;
import sirius.db.mixing.PropertyValidator;
import sirius.kernel.commons.Strings;
import sirius.kernel.di.std.Register;
import sirius.kernel.health.Exceptions;
import sirius.kernel.health.HandledException;
import javax.annotation.Nonnull;
import java.util.function.Consumer;
import java.util.regex.Pattern;
/**
* Validates that the stored value in a string property is a valid telephone number.
*/
@Register
public class PhoneNumberValidator implements PropertyValidator {
/**
* Matches a part of a phone number like <tt>55 55</tt> or <tt>55</tt>.
*/
private static final String NUMERIC_PART = "( *\\d+)*+";
/**
* Validates a phone number.
*/
public static final Pattern VALID_PHONE_NUMBER =
Pattern.compile("\\+?\\d+" + NUMERIC_PART + "( */" + NUMERIC_PART + ")?( *-" + NUMERIC_PART + ")?");
@Override
public void validate(Property property, Object value, Consumer<String> validationConsumer) {
if (value instanceof String phoneNumber && Strings.isFilled(phoneNumber) && !VALID_PHONE_NUMBER.matcher(
phoneNumber).matches()) {
validationConsumer.accept(createInvalidPhoneException(property, phoneNumber).getMessage());
}
}
@Override
public void beforeSave(Property property, Object value) {
if (value instanceof String phoneNumber && Strings.isFilled(phoneNumber) && !VALID_PHONE_NUMBER.matcher(
phoneNumber).matches()) {
throw createInvalidPhoneException(property, phoneNumber);
}
}
private HandledException createInvalidPhoneException(Property property, String value) {
return Exceptions.createHandled()
.withNLSKey("ContactData.invalidPhone")
.set("field", property.getLabel())
.set("value", value)
.handle();
}
@Nonnull
@Override
public String getName() {
return "phone-number-validator";
}
}