diff --git a/src/decorator/string/IsPhoneNumber.spec.ts b/src/decorator/string/IsPhoneNumber.spec.ts new file mode 100644 index 0000000000..dc182e509c --- /dev/null +++ b/src/decorator/string/IsPhoneNumber.spec.ts @@ -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); + }); + }); +}); diff --git a/src/decorator/string/IsPhoneNumber.ts b/src/decorator/string/IsPhoneNumber.ts index 2a359138ae..039284f0a8 100644 --- a/src/decorator/string/IsPhoneNumber.ts +++ b/src/decorator/string/IsPhoneNumber.ts @@ -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'; @@ -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); } /**