1
2
3
4 package de.powerstat.validation.values;
5
6
7 import java.util.Objects;
8 import java.util.regex.Pattern;
9
10 import de.powerstat.validation.interfaces.IValueObject;
11
12
13
14
15
16
17
18
19
20
21
22
23 public final class PostalCode implements Comparable<PostalCode>, IValueObject
24 {
25
26
27
28
29
30
31
32
33 private static final Pattern POSTALCODE_REGEXP = Pattern.compile("^[0-9A-Z -]{3,11}$");
34
35
36
37
38 private final String postalCode;
39
40
41
42
43
44
45
46
47
48 private PostalCode(final String postalCode)
49 {
50 super();
51 Objects.requireNonNull(postalCode, "postalCode");
52 if ((postalCode.length() < 3) || (postalCode.length() > 11))
53 {
54 throw new IllegalArgumentException("postalCode with wrong length");
55 }
56 if (!PostalCode.POSTALCODE_REGEXP.matcher(postalCode).matches())
57 {
58 throw new IllegalArgumentException("postalCode with wrong format");
59 }
60 this.postalCode = postalCode;
61 }
62
63
64
65
66
67
68
69
70 public static PostalCode of(final String postalCode)
71 {
72
73
74
75
76
77
78
79
80
81
82
83
84
85 return new PostalCode(postalCode);
86 }
87
88
89
90
91
92
93
94 @Override
95 public String stringValue()
96 {
97 return this.postalCode;
98 }
99
100
101
102
103
104
105
106
107 @Override
108 public int hashCode()
109 {
110 return this.postalCode.hashCode();
111 }
112
113
114
115
116
117
118
119
120
121 @Override
122 public boolean equals(final Object obj)
123 {
124 if (this == obj)
125 {
126 return true;
127 }
128 if (!(obj instanceof PostalCode))
129 {
130 return false;
131 }
132 final PostalCode other = (PostalCode)obj;
133 return this.postalCode.equals(other.postalCode);
134 }
135
136
137
138
139
140
141
142
143
144
145
146
147 @Override
148 public String toString()
149 {
150 final var builder = new StringBuilder(23);
151 builder.append("PostalCode[postalCode=").append(this.postalCode).append(']');
152 return builder.toString();
153 }
154
155
156
157
158
159
160
161
162
163 @Override
164 public int compareTo(final PostalCode obj)
165 {
166 Objects.requireNonNull(obj, "obj");
167 return this.postalCode.compareTo(obj.postalCode);
168 }
169
170 }