Repository navigation
Expand file tree
/
Copy pathEmailValidator.java
More file actions
61 lines (46 loc) · 1.63 KB
/
Copy pathEmailValidator.java
File metadata and controls
61 lines (46 loc) · 1.63 KB
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
import java.util.regex.Pattern;
public final class EmailValidator {
private static final int MAX_EMAIL_LENGTH = 254;
// Simple email format validation
private static final String EMAIL_REGEX =
"^[a-zA-Z0-9_+%*-]+(?:\\.[a-zA-Z0-9_+%*-]+)*"
+ "@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}$";
private static final Pattern EMAIL_PATTERN =
Pattern.compile(EMAIL_REGEX);
private EmailValidator() {
// Utility class: instantiation is not required
}
public static String validate(String email) {
if (email == null || email.isBlank()) {
throw new InvalidEmailException(
"Email address cannot be null or blank."
);
}
String trimmedEmail = email.trim();
if (trimmedEmail.length() > MAX_EMAIL_LENGTH) {
throw new InvalidEmailException(
"Email address exceeds the maximum length of "
+ MAX_EMAIL_LENGTH + " characters."
);
}
if (!EMAIL_PATTERN.matcher(trimmedEmail).matches()) {
throw new InvalidEmailException(
"Invalid email address format: " + trimmedEmail
);
}
return trimmedEmail;
}
public static boolean isValid(String email) {
try {
validate(email);
return true;
} catch (InvalidEmailException exception) {
return false;
}
}
public static class InvalidEmailException extends RuntimeException {
public InvalidEmailException(String message) {
super(message);
}
}
}