Skip to content

Commit

Permalink
Merge pull request #65 from City-of-Helsinki/fix/LINK-1530-phone-vali…
Browse files Browse the repository at this point in the history
…dation

LINK-1530 | Improve phone number validation
  • Loading branch information
jorilindell authored Sep 8, 2023
2 parents 24d1815 + 015f687 commit f87ebc2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
40 changes: 39 additions & 1 deletion src/utils/__tests__/validationUtils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getErrorText } from '../validationUtils';
import { getErrorText, isValidPhoneNumber } from '../validationUtils';

describe('getErrorText', () => {
it('should return error text', () => {
Expand All @@ -13,3 +13,41 @@ describe('getErrorText', () => {
expect(t).toBeCalledWith(error.key, error);
});
});

describe('isValidPhoneNumber function', () => {
const validCases: string[][] = [
['0441234567'],
['044 1234 567'],
['044 123 4567'],
['044 1234567'],
['+358441234567'],
['+358 44 123 4567'],
['+358 44 1234 567'],
['+358 441234567'],
];
test.each(validCases)(
'should return true value if phone number is valid, %p',
async (phoneNumber) => {
expect(isValidPhoneNumber(phoneNumber)).toBe(true);
}
);

const invalidCases: string[][] = [
['044 1234 56x'],
['044 123x 567'],
['04x 1234 567'],
['044 1234 567'],
['044 123 4567'],
['044 1234567'],
['+358 44 123 4567'],
['+358 44 123 4567'],
['+358 44 1234 567'],
['+358 441234567'],
];
test.each(invalidCases)(
'should return false value if phone number is invalid, %p',
async (phoneNumber) => {
expect(isValidPhoneNumber(phoneNumber)).toBe(false);
}
);
});
2 changes: 1 addition & 1 deletion src/utils/validationUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const createMinErrorMessage = (
};

export const isValidPhoneNumber = (phone: string): boolean =>
/^\+?\(?\d{1,3}\)? ?-?\d{1,3} ?-?\d{3,5} ?-?\d{4}( ?-?\d{3})?/.test(phone);
/^\+?\(?\d{1,3}\)? ?-?\d{1,3} ?-?\d{3,5} ?-?\d{3,4}( ?-?\d{3})?/.test(phone);

export const isValidZip = (zip: string): boolean => /^\d{5}$/.test(zip);

Expand Down

0 comments on commit f87ebc2

Please sign in to comment.