Skip to content

Commit

Permalink
feat: update IsPhoneNumber decorator to use max dataset
Browse files Browse the repository at this point in the history
  • Loading branch information
NoNameProvided committed Dec 15, 2022
1 parent d325cc7 commit 9876eea
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
33 changes: 33 additions & 0 deletions src/decorator/string/IsPhoneNumber.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { isPhoneNumber } from './IsPhoneNumber';

describe('@IsPhoneNumber decorator implementation', () => {
describe('isPhoneNumber validator', () => {
it('should accept valid values', () => {
expect(isPhoneNumber('+36 20 111 1111', 'HU')).toBe(true);
});

describe('should not accept invalid values', () => {
it('when country code invalid', () => {
expect(isPhoneNumber('+1 20 111 1111', 'HU')).toBe(false);
});

it('when country code does not match locale', () => {
expect(isPhoneNumber('+36 00 111 1111', 'HU')).toBe(false);
});

it('when phone number length is incorrect', () => {
expect(isPhoneNumber('+36 20 111 111', 'HU')).toBe(false);
});

it('when there are letters after or before the phone number', () => {
expect(isPhoneNumber('abc +36 20 111 111', 'HU')).toBe(false);
expect(isPhoneNumber('+36 20 111 111 abc', 'HU')).toBe(false);
});
});

it('should not accept values with extra whitespace', () => {
expect(isPhoneNumber(' +36 20 111 1111', 'HU')).toBe(false);
expect(isPhoneNumber('+36 20 111 1111 ', 'HU')).toBe(false);
});
});
});
13 changes: 5 additions & 8 deletions src/decorator/string/IsPhoneNumber.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ValidationOptions } from '../ValidationOptions';
import { buildMessage, ValidateBy } from '../common/ValidateBy';
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js';
import { isValidPhoneNumber, CountryCode } from 'libphonenumber-js/max';

export const IS_PHONE_NUMBER = 'isPhoneNumber';

Expand All @@ -13,14 +13,11 @@ export const IS_PHONE_NUMBER = 'isPhoneNumber';
* If text doesn't start with the international calling code (e.g. +41), then you must set this parameter.
*/
export function isPhoneNumber(value: string, region?: CountryCode): boolean {
try {
const phoneNum = parsePhoneNumberFromString(value, region);
const result = phoneNum?.isValid();
return !!result;
} catch (error) {
// logging?
return false;
if(typeof value !== 'string' || value.trim() !== value) {
return false
}

return isValidPhoneNumber(value, region);
}

/**
Expand Down

0 comments on commit 9876eea

Please sign in to comment.