Skip to content

Commit

Permalink
Fix CheckPostalCode to only pass valid inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
evnaz committed Oct 27, 2023
1 parent 2ba5803 commit ef7238a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
12 changes: 10 additions & 2 deletions address.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,21 @@ func (f Format) CheckRegion(region string) bool {
//
// An empty postal code is considered valid.
func (f Format) CheckPostalCode(postalCode string) bool {
if postalCode == "" || f.PostalCodePattern == "" {
if postalCode == "" {
return true
}
rx := regexp.MustCompile(f.PostalCodePattern)
rx := regexp.MustCompile(f.PostalCodeValidationPattern())
return rx.MatchString(postalCode)
}

// PostalCodeValidationPattern returns the full regex pattern for validating the postal code.
func (f *Format) PostalCodeValidationPattern() string {
if f.PostalCodePattern == "" {
return "^.+$"
}
return "^" + f.PostalCodePattern + "$"
}

// SelectLayout selects the correct layout for the given locale.
func (f Format) SelectLayout(locale Locale) string {
if f.LocalLayout != "" && f.useLocalData(locale) {
Expand Down
4 changes: 3 additions & 1 deletion address_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,9 @@ func TestFormat_CheckPostalCode(t *testing.T) {
// Valid postal code.
{"FR", "75002", true},
// Invalid postal code.
{"FR", "INVALID", false},
{"FR", "A75002", false},
// Invalid postal code.
{"FR", "75002B", false},
// Country with no predefined pattern.
{"AG", "AG123", true},
}
Expand Down

0 comments on commit ef7238a

Please sign in to comment.