UNPKG

@socoe/mykad

Version:

Library to validate, parse, generate, and format Malaysian identity card (MyKad) numbers

76 lines (71 loc) 2.26 kB
"use strict"; var birthplace = require('./birthplace'); var random = require('./random'); // Check if date is before disregarding year. function dateIsBefore(before, max) { var bNorm = new Date(0, before.getMonth(), before.getDate()); var mNorm = new Date(0, max.getMonth(), max.getDate()); return bNorm < mNorm; } function codeToDate(year, month, day) { var today = new Date(); // Prevents the date from being set to 29th February 1900. // Special case as 29th February 2000 is a valid date. if (year === '00') { year = today.getFullYear().toString().slice(0, 2) + '00'; } var birthDate = new Date(year, month - 1, day); var age = today.getFullYear() - birthDate.getFullYear(); // Works for now. Update this in year 2099. // For same year, checks if date has passed. if (age > 100 || age == 100 && dateIsBefore(birthDate, today)) { birthDate.setFullYear(birthDate.getFullYear() + 100); } // Check valid date. return birthDate.getDate() == day && birthDate.getMonth() == month - 1 ? birthDate : NaN; } function codeToGender(code) { return code % 2 === 0 ? 'female' : 'male'; } function extractParts(icNum) { var regex = /^(\d{2})(\d{2})(\d{2})-?(\d{2})-?(\d{3})(\d{1})$/; var parts = icNum.match(regex); if (!parts) { throw new Error('Invalid MyKad number format'); } return parts; } function isValid(icNum) { var parts; try { parts = extractParts(icNum); } catch (error) { return false; } var birthDate = codeToDate(parts[1], parts[2], parts[3]); return !isNaN(birthDate) && birthplace.isValid(parts[4]); } function parse(icNum) { var parts = extractParts(icNum); var parsedData = { birthDate: codeToDate(parts[1], parts[2], parts[3]), birthPlace: birthplace.parse(parts[4]), gender: codeToGender(parts[6]) }; return parsedData; } function format(icNum) { var parts = extractParts(icNum); return "".concat(parts[1]).concat(parts[2]).concat(parts[3], "-").concat(parts[4], "-").concat(parts[5]).concat(parts[6]); } function unformat(icNum) { var formatted = format(icNum); return formatted.replace(/-/g, ''); } module.exports = { isValid: isValid, parse: parse, format: format, unformat: unformat, generateRandom: random.generateRandom };