degachejs
Version:
A Tunisian utility library for working with CIN, phone numbers, addresses, and more
48 lines (47 loc) • 1.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCarrierInfo = exports.validatePhoneNumber = void 0;
const constants_1 = require("../constants");
/**
* Regular expressions for phone number validation
*/
const REGEX = {
PHONE: /^[2-9]\d{7}$/,
INTERNATIONAL: /^\+216[2-9]\d{7}$/,
// Strict mode allows only digits and optional +216 prefix
STRICT_PHONE: /^(?:\+216)?[2-9]\d{7}$/,
};
/**
* Validates a Tunisian phone number
* @param phoneNumber - The phone number to validate
* @param options - Validation options
* @returns boolean indicating if the phone number is valid
*/
const validatePhoneNumber = (phoneNumber, options = {}) => {
if (!phoneNumber)
return false;
// In strict mode, validate against the strict regex first
if (options.strict && !REGEX.STRICT_PHONE.test(phoneNumber)) {
return false;
}
// Remove international prefix if present
const normalizedNumber = phoneNumber.replace(/^\+216/, "");
if (!REGEX.PHONE.test(normalizedNumber))
return false;
return constants_1.VALID_PREFIXES.includes(normalizedNumber[0]);
};
exports.validatePhoneNumber = validatePhoneNumber;
/**
* Gets carrier information from a phone number
* @param phoneNumber - The phone number to check
* @param options - Validation options
* @returns carrier information or null if invalid
*/
const getCarrierInfo = (phoneNumber, options = {}) => {
if (!(0, exports.validatePhoneNumber)(phoneNumber, options))
return null;
const normalizedNumber = phoneNumber.replace(/^\+216/, "");
const prefix = normalizedNumber[0];
return (Object.entries(constants_1.CARRIERS).find(([_, carrier]) => carrier.prefixes.includes(prefix))?.[1] || null);
};
exports.getCarrierInfo = getCarrierInfo;