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

Conversation

evnaz
Copy link
Contributor

@evnaz evnaz commented Oct 27, 2023

This pull request addresses an issue with the postal code validation in the library, which currently returns true for inputs that contain valid postal codes but also include additional, invalid characters. For example, the current regex for France would validate "A12345" as a valid postal code, even though it contains an invalid character "A".

To fix this, I've introduced a new function on the Format type that returns a modified version for the postal code regex by adding start ^ and end $ anchors, ensuring that the regex will only pass if the entire input string is a valid postal code, with no additional characters, and use this modified pattern in the CheckPostalCode. The underlying PostalCodePattern remains intact as it might be useful for matching, e.g. extracting postal code from the full address string.

@@ -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.

@bojanz
Copy link
Owner

bojanz commented Oct 28, 2023

Great catch, thanks! I have a single question (posted above), then we can proceed with merging and releasing this.

@evnaz evnaz requested a review from bojanz October 30, 2023 06:51
@bojanz bojanz merged commit ddb2193 into bojanz:master Oct 31, 2023
@bojanz
Copy link
Owner

bojanz commented Oct 31, 2023

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants