Skip to content

Instantly share code, notes, and snippets.

@peatiscoding
Created September 4, 2021 00:14
Show Gist options
  • Save peatiscoding/a16840caed0ba1b29e6b2fe171565ea0 to your computer and use it in GitHub Desktop.
Save peatiscoding/a16840caed0ba1b29e6b2fe171565ea0 to your computer and use it in GitHub Desktop.
Validate Thai Id (checksum) using TypeScript
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