Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix CheckPostalCode to Validate Input Strictly #3

Merged
merged 2 commits into from
Oct 31, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 == "" {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A PostalCodePattern tends to be empty only if a format does not have a postalCode field at all. In which case the current check might be enough? Or do we gain anything by compiling a "^.+$" regexp and matching the postalCode against it in that case?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the context! Not sure if it's good to report true when the format doesn't require a postal code and the input is a non empty string. Probably ^$ regex would make more sense in that case as then you can detect that there's something unexpected provided.

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