Skip to content

Commit

Permalink
-Validate was not quite a validate
Browse files Browse the repository at this point in the history
  • Loading branch information
florinTAPP committed Dec 16, 2021
1 parent 57cff6d commit dd93074
Showing 1 changed file with 2 additions and 21 deletions.
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

0 comments on commit dd93074

Please sign in to comment.