Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use modern JS constructs to validate NRIC #2785

Merged
merged 3 commits into from
Sep 20, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 24 additions & 32 deletions shared/utils/nric-validation.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,33 @@
type NricParts = {
prefix: string
digits: string
checksum: string
}

const NRIC_FORMAT = /^(?<prefix>[STFG])(?<digits>\d{7})(?<checksum>[A-Z])$/

/**
* Validates whether a provided string value adheres to the UIN/FIN format
* as provided on the Singapore Government's National Registration Identity Card.
* @param value The value to be validated
*/
export const isNricValid = (value: string): boolean => {
return isFormatValid(value) && isChecksumValid(value)
}
const parsed = value?.toUpperCase().match(NRIC_FORMAT)

/**
* Tests whether a provided string value obeys a simple format check
* @param value The value to be validated
*/
const isFormatValid = (value: string): boolean => {
return /^([STFGstfg]{1})([0-9]{7})([A-Za-z]{1})$/.test(value)
}
if (!parsed) return false

/**
* Algorithm to test whether the NRIC checksum is valid
* @param value The value to be validated
*/
const isChecksumValid = (value: string): boolean => {
// http://www.ngiam.net/NRIC/NRIC_numbers.pdf
value = value.toUpperCase()
const prefix = value.charAt(0)
const suffix = value.charAt(value.length - 1)
const coefficients = [2, 7, 6, 5, 4, 3, 2]
const constant = prefix === 'S' || prefix === 'F' ? 0 : 4
const coding =
prefix === 'S' || prefix === 'T'
? ['J', 'Z', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']
: ['X', 'W', 'U', 'T', 'R', 'Q', 'P', 'N', 'M', 'L', 'K']
const sum = value
.substring(1, value.length - 1)
.split('')
.reduce(function (sum, digit, idx) {
sum += parseInt(digit) * coefficients[idx]
return sum
}, constant)
return suffix === coding[sum % 11]
const { prefix, digits, checksum } = parsed.groups as NricParts

// Specifications at: http://www.ngiam.net/NRIC/NRIC_numbers.pdf
const weights = [2, 7, 6, 5, 4, 3, 2]
const startConstant = prefix === 'S' || prefix === 'F' ? 0 : 4
const checksumEncoding =
prefix === 'S' || prefix === 'T' ? 'JZIHGFEDCBA' : 'XWUTRQPNMLK'

const weightedSum = weights.reduce(
(acc, weight, idx) => acc + weight * parseInt(digits[idx]),
startConstant,
)

return checksum === checksumEncoding[weightedSum % 11]
}