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

feat: update @IsPhoneNumber decorator to use max dataset #1857

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
});
});
11 changes: 4 additions & 7 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?
if (typeof value !== 'string' || value.trim() !== value) {
return false;
}

return isValidPhoneNumber(value, region);
}

/**
Expand Down