import { Localize } from '../Application'; const formatNumberToMoney = (number: number, currency = '') => { if (!number || isNaN(number) || Number(number) === 0) { return `0${currency}`; } const array: string[] = []; let result = ''; let isNegative = false; if (number < 0) { isNegative = true; } const numberString = Math.abs(number).toString(); if (numberString.length < 3) { return isNegative ? `-${numberString}${currency}` : `${numberString}${currency}`; } let count = 0; for (let i = numberString.length - 1; i >= 0; i -= 1) { count += 1; if (numberString[i] === '.' || numberString[i] === ',') { array.push(','); count = 0; } else { array.push(numberString[i] as string); } if (count === 3 && i >= 1) { array.push('.'); count = 0; } } for (let i = array.length - 1; i >= 0; i -= 1) { result += array[i]; } return isNegative ? `-${result}${currency}` : `${result}${currency}`; }; const formatMoneyToNumber = (money: string, currencyUnit: string) => { if (money && money.length > 0) { const moneyString = money .replace(currencyUnit, '') .replace(/,/g, '') .replace(/đ/g, '') .replace(/\./g, '') .replace(/ /g, ''); const number = Number(moneyString); if (isNaN(number)) { return 0; } return number; } return Number(money); }; // --- PHONE VALIDATION --- function formatPhoneNumber(phone: string): string { return phone.replace(/\D/g, ''); } function checkValidPhoneNumber(phone: string): { phoneFormatted: string; error?: string; } { let phoneNumber = phone; // if not starting with 0 and has 9 digits => prepend 0 if ( phoneNumber.length > 0 && phoneNumber[0] !== '0' && /^\d$/.test(phoneNumber[0]) && phoneNumber.length === 9 ) { phoneNumber = '0' + phoneNumber; } const phoneFormatted = formatPhoneNumber(phoneNumber); const localize = new Localize({ vi: {}, en: {} }); let error: string | undefined; if (phoneFormatted.length === 0) { error = localize.translate('enterPhoneNumber'); } else if (phoneFormatted.length < 10 || phoneFormatted.length > 11) { error = localize.translate('invalidPhoneNumber'); } return { phoneFormatted: phoneFormatted, error }; } export { formatMoneyToNumber, formatNumberToMoney, checkValidPhoneNumber };