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

fix: IsPhoneNumber decorator did not validate correctly #1454

Closed
wants to merge 1 commit into from
Closed
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
23 changes: 2 additions & 21 deletions src/decorator/string/IsPhoneNumber.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,9 @@
import { ValidationOptions } from '../ValidationOptions';
import { buildMessage, ValidateBy } from '../common/ValidateBy';
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js';
import { isValidPhoneNumber, CountryCode } from 'libphonenumber-js';

export const IS_PHONE_NUMBER = 'isPhoneNumber';

/**
* Checks if the string is a valid phone number. To successfully validate any phone number the text must include
* the intl. calling code, if the calling code wont be provided then the region must be set.
*
* @param value the potential phone number string to test
* @param region 2 characters uppercase country code (e.g. DE, US, CH) for country specific validation.
* 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;
}
}

/**
* Checks if the string is a valid phone number. To successfully validate any phone number the text must include
* the intl. calling code, if the calling code wont be provided then the region must be set.
Expand All @@ -36,7 +17,7 @@ export function IsPhoneNumber(region?: CountryCode, validationOptions?: Validati
name: IS_PHONE_NUMBER,
constraints: [region],
validator: {
validate: (value, args): boolean => isPhoneNumber(value, args?.constraints[0]),
validate: (value, args): boolean => isValidPhoneNumber(value, args?.constraints[0]),
defaultMessage: buildMessage(
eachPrefix => eachPrefix + '$property must be a valid phone number',
validationOptions
Expand Down