@@ -12,7 +12,15 @@ sys.setdefaultencoding('utf8')
12
12
}%
13
13
% with open(os.getcwd() + "/../../Resources/postalData.json") as file:
14
14
%{ data = json.load(file) }%
15
+ /// A validator for postal codes.
15
16
public final class PostalCodeValidator {
17
+ /**
18
+ * A set of available region codes.
19
+ *
20
+ * Each element of the returned set is an two-letter
21
+ * ISO 3166-2 region code
22
+ * (for example, "US" for the United States of America).
23
+ */
16
24
public class var isoRegionCodes: Set<String> {
17
25
return Set(patternsByRegion.keys)
18
26
}
@@ -32,10 +40,22 @@ public final class PostalCodeValidator {
32
40
% end
33
41
]
34
42
43
+ /// The locale of the validator.
35
44
public private(set) var locale: Locale
36
45
private var regularExpression: NSRegularExpression
37
46
38
- public init?(locale: Locale = .autoupdatingCurrent) {
47
+ /**
48
+ * Creates a postal code validator for the region of the provided locale.
49
+ *
50
+ * If the locale doesn't specify a valid region,
51
+ * or the region isn't supported,
52
+ * this initializer returns `nil`.
53
+ *
54
+ * - Parameters:
55
+ * - locale: The locale whose `regionCode` property is used to determine
56
+ * the appropriate postal code validation rules.
57
+ */
58
+ public init?(locale: Locale = .current) {
39
59
self.locale = locale
40
60
guard let regionCode = locale.regionCode,
41
61
let pattern = PostalCodeValidator.patternsByRegion[regionCode],
@@ -45,6 +65,13 @@ public final class PostalCodeValidator {
45
65
self.regularExpression = regex
46
66
}
47
67
68
+ /**
69
+ * Returns whether a postal code is valid for the configured region.
70
+ *
71
+ * - Parameters:
72
+ * - postalCode: The postal code.
73
+ * - Returns: `true` if valid, otherwise `false`.
74
+ */
48
75
public func validate(postalCode: String) -> Bool {
49
76
return regularExpression.rangeOfFirstMatch(in: postalCode, options: [], range: NSRange(postalCode.startIndex..<postalCode.endIndex, in: postalCode)).location != NSNotFound
50
77
}
0 commit comments