1+ import { PhoneNumberType } from '../../utils/phone-number-type' ;
12import { ValidationOptions } from '../ValidationOptions' ;
23import { buildMessage , ValidateBy } from '../common/ValidateBy' ;
3- import { parsePhoneNumber , CountryCode } from 'libphonenumber-js/max' ;
4+
5+ /* Changed import to /max for all metadata provided in the library in order to check phone number type
6+ * since the (default = /min) always returns undefined in the .getType()
7+ * reference https://www.npmjs.com/package/libphonenumber-js
8+ */
9+ import { parsePhoneNumberFromString , CountryCode } from 'libphonenumber-js/max' ;
410
511export const IS_PHONE_NUMBER = 'isPhoneNumber' ;
612
@@ -10,26 +16,30 @@ export const IS_PHONE_NUMBER = 'isPhoneNumber';
1016 *
1117 * @param value the potential phone number string to test
1218 * @param region 2 characters uppercase country code (e.g. DE, US, CH) for country specific validation.
19+ * @param acceptedNumbersTypes list of accepted number types (MOBILE, PAGER, etc...) if not provided check only MOBILE.
1320 * If text doesn't start with the international calling code (e.g. +41), then you must set this parameter.
1421 */
15- export function isPhoneNumber ( value : string , region ?: CountryCode ) : boolean {
16- if ( typeof value !== ' string' || value . trim ( ) !== value ) {
17- return false ;
18- }
19-
22+ export function isPhoneNumber (
23+ value : string ,
24+ region ?: CountryCode ,
25+ acceptedNumbersTypes ?: Array < PhoneNumberType >
26+ ) : boolean {
2027 try {
21- const phoneNumber = parsePhoneNumber ( value , region ) ;
28+ // the list of all phone number types that are the output of .getType() method
29+ let checkedNumberTypes = [ 'MOBILE' ] ;
2230
23- /**
24- * We fail the validation if the user provided a region code
25- * and it doesn't match with the country code of the parsed number.
26- **/
27- if ( region && phoneNumber . country !== region ) {
28- return false ;
31+ // Checking if accepted types array is passed to override the default MOBILE number type
32+ if ( acceptedNumbersTypes ) {
33+ checkedNumberTypes = acceptedNumbersTypes ;
2934 }
3035
31- return phoneNumber . isValid ( ) ;
36+ const phoneNum = parsePhoneNumberFromString ( value , region ) ;
37+
38+ // number must be valid and is one of the phone types the function accepts (ALL TYPES PROVIDED IN phone-number-types.ts)
39+ const result : boolean = ! ! phoneNum ?. isValid ( ) && ! ! checkedNumberTypes . some ( item => item === phoneNum ?. getType ( ) ) ;
40+ return ! ! result ;
3241 } catch ( error ) {
42+ // logging?
3343 return false ;
3444 }
3545}
0 commit comments