Created
September 4, 2021 00:14
-
-
Save peatiscoding/a16840caed0ba1b29e6b2fe171565ea0 to your computer and use it in GitHub Desktop.
Validate Thai Id (checksum) using TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assertThaiId = (thaiId: string): boolean => { | |
const m = thaiId.match(/(\d{12})(\d)/) | |
if (!m) { | |
console.warn('Bad input from user, invalid thaiId=', thaiId) | |
throw new Error('thai-id-must-be-13-digits') | |
} | |
const digits = m[1].split(''); | |
const sum = digits.reduce((total: number, digit: string, i: number) => { | |
return total + (13 - i) * +digit; | |
}, 0) | |
const lastDigit = `${(11 - sum % 11) % 10}` | |
const inputLastDigit = m[2] | |
if (lastDigit !== inputLastDigit) { | |
console.warn('Bad input from user, invalid checksum thaiId=', thaiId) | |
throw new Error('thai-id-checksum-mismatched') | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment