UNPKG

eg-id-validate

Version:

A javascript library to validate the Egyptian ID

55 lines (43 loc) 1.67 kB
/* Error types: 1: non string type of id 2: id of invalid length 3: id has invalid century, only 1,2 and 3 are accepted 4: id has invalid date of birth */ exports.checker = function (nid) { const id = nid.trim() const d = new Date() const this_year = d.getFullYear()-2000 const this_month = d.getMonth()+1 //assert argument type to be string if (typeof id !== "string") return {valid: false, error_code: 1} //check id length if (id.length !== 14) return {valid: false, error_code: 2} const century = parseInt(id.substr(0,1)) const year = parseInt(id.substr(1,2)) const month = parseInt(id.substr(3,2)) const day = parseInt(id.substr(5,2)) const gov = parseInt(id.substr(7,2)) const sex = parseInt(id.substr(12,1))%2? 'm':'f' //check century value if (! [2,3].includes(century)) return {valid: false, error_code: 3} //check date of birth if (year<20 && century===2) return {valid: false, error_code: 4} if (year>this_year && century===3) return {valid: false, error_code: 4} if (month>12) return {valid: false, error_code: 4} if (month>this_month && year===this_year) return {valid: false, error_code: 4} if (day>31) return {valid: false, error_code: 4} if (month===2 && day>29) return {valid: false, error_code: 4} if ([4,6,9,11].includes(month)&& day>30) return {valid: false, error_code: 4} //check governorate if (gov<1) return {valid: false, error_code: 5} if (gov>35 && gov!==86 && gov!==88) return {valid: false, error_code: 5} return { valid: true, age: 10, gov: gov, dob: "", sex: sex } }