Skip to content

Commit

Permalink
fix(validator): improve sanitizePhoneNumber structure
Browse files Browse the repository at this point in the history
  • Loading branch information
mohammadhonarvar authored and alimd committed Apr 25, 2023
1 parent 0345add commit fb90f2f
Showing 1 changed file with 7 additions and 15 deletions.
22 changes: 7 additions & 15 deletions core/validator/src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,32 +145,24 @@ export function validator<T extends StringifyableRecord>(
*/
export const sanitizeString = (str: string, replaceNumberToLang: UnicodeLangKeys = 'en'): string => {
if (!str) return '';
const unicodeDigits = new UnicodeDigits(replaceNumberToLang, 'all');
const unicodeDigits = new UnicodeDigits(replaceNumberToLang);
str = unicodeDigits.translate(str);
return str.replace(/\s/g, '');
};

const phoneJungRegExp = /^98|^0098|^00989|^0|^\+98/;
/**
* Coverts an input to a valid and sanitized phone number
*/
export const sanitizePhoneNumber = (input?: string | number | null): number | null => {
if (input == null) return null;

if (typeof input === 'number') input = input + '';
input = sanitizeString(input);
input = '98' + input.replace(phoneJungRegExp, '');
input = input.replace(/[ )(+-]+/g, '');

return +input;
};

const validPhoneRegExp = /\+989(9[0-9]|0[1-2]|1[0-9]|3[0-9]|2[0-1])-?[0-9]{3}-?[0-9]{4}$/;
/**
* Checks an input is a valid phone number or not
*/
export const validatePhone = (phone: string, skipSanitize = false): boolean => {
if (!skipSanitize) {
phone = sanitizePhoneNumber(phone) + '';
if (!input.startsWith('98')) {
input = '98' + input;
}
return validPhoneRegExp.test(phone);
if (!isNumber(input)) return null;

return +input;
};

0 comments on commit fb90f2f

Please sign in to comment.