Skip to content

Commit

Permalink
fix: Make whitespace postal code invalid
Browse files Browse the repository at this point in the history
  • Loading branch information
ibooker committed May 28, 2024
1 parent 4d4e408 commit 69f7739
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/__tests__/postal-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ describe("postalCode", () => {
[["hello world", { isValid: true, isPotentiallyValid: true }]],
],

[
"returns isPotentiallyValid for strings without alphanumeric first three characters",
[
["123", { isValid: true, isPotentiallyValid: true }],
[" 123", { isValid: true, isPotentiallyValid: true }],
["---", { isValid: false, isPotentiallyValid: true }],
[" ---", { isValid: false, isPotentiallyValid: true }],
],
],

[
"returns isPotentiallyValid for shorter-than-3 strings",
[
Expand Down Expand Up @@ -87,6 +97,10 @@ describe("postalCode", () => {
isValid: true,
isPotentiallyValid: true,
});
expect(postalCode(" -$%", { minLength: 0 })).toEqual({
isValid: false,
isPotentiallyValid: true,
});
});
});
});
3 changes: 3 additions & 0 deletions src/postal-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ type PostalCodeOptions = {
};

const DEFAULT_MIN_POSTAL_CODE_LENGTH = 3;
const ALPHANUM = new RegExp(/^[a-z0-9]+$/i);

function verification(
isValid: boolean,
Expand All @@ -23,6 +24,8 @@ export function postalCode(
return verification(false, false);
} else if (value.length < minLength) {
return verification(false, true);
} else if (!ALPHANUM.test(value.trim().slice(0, minLength))) {
return verification(false, true);
}

return verification(true, true);
Expand Down

0 comments on commit 69f7739

Please sign in to comment.