Skip to content

Commit ddb2193

Browse files
authored
Fix CheckPostalCode to Validate Input Strictly (#3)
* Fix CheckPostalCode to only pass valid inputs * Reject non-empty postal codes if not required
1 parent 6f2ba1c commit ddb2193

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

address.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -83,13 +83,18 @@ func (f Format) CheckRegion(region string) bool {
8383
//
8484
// An empty postal code is considered valid.
8585
func (f Format) CheckPostalCode(postalCode string) bool {
86-
if postalCode == "" || f.PostalCodePattern == "" {
86+
if postalCode == "" {
8787
return true
8888
}
89-
rx := regexp.MustCompile(f.PostalCodePattern)
89+
rx := regexp.MustCompile(f.PostalCodeValidationPattern())
9090
return rx.MatchString(postalCode)
9191
}
9292

93+
// PostalCodeValidationPattern returns the full regex pattern for validating the postal code.
94+
func (f *Format) PostalCodeValidationPattern() string {
95+
return "^" + f.PostalCodePattern + "$"
96+
}
97+
9398
// SelectLayout selects the correct layout for the given locale.
9499
func (f Format) SelectLayout(locale Locale) string {
95100
if f.LocalLayout != "" && f.useLocalData(locale) {

address_test.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,13 @@ func TestFormat_CheckPostalCode(t *testing.T) {
108108
// Valid postal code.
109109
{"FR", "75002", true},
110110
// Invalid postal code.
111-
{"FR", "INVALID", false},
111+
{"FR", "A75002", false},
112+
// Invalid postal code.
113+
{"FR", "75002B", false},
114+
// Country with no predefined pattern.
115+
{"AG", "AG123", false},
112116
// Country with no predefined pattern.
113-
{"AG", "AG123", true},
117+
{"AG", "", true},
114118
}
115119

116120
for _, tt := range tests {

0 commit comments

Comments
 (0)