pak-cnic-utils
Version:
A simple utility to validate and generate Pakistani CNIC numbers
32 lines (26 loc) • 855 B
JavaScript
// index.js
// Validate CNIC format XXXXX-XXXXXXX-X
function isValidCNIC(cnic) {
const regex = /^[0-9]{5}-[0-9]{7}-[0-9]{1}$/;
return regex.test(cnic);
}
// Generate a fake CNIC in the correct format
function generateFakeCNIC() {
const getRandomDigits = (length) =>
Array.from({ length }, () => Math.floor(Math.random() * 10)).join('');
const part1 = getRandomDigits(5);
const part2 = getRandomDigits(7);
const part3 = getRandomDigits(1);
return `${part1}-${part2}-${part3}`;
}
// Format CNIC (remove any existing formatting and reformat it)
function formatCNIC(raw) {
const digits = raw.replace(/\D/g, ''); // Remove non-digit characters
if (digits.length !== 13) return null;
return `${digits.slice(0, 5)}-${digits.slice(5, 12)}-${digits.slice(12)}`;
}
module.exports = {
isValidCNIC,
generateFakeCNIC,
formatCNIC,
};