Skip to content

Commit

Permalink
fix: lint
Browse files Browse the repository at this point in the history
  • Loading branch information
jukbot committed Sep 17, 2024
1 parent 6a003fe commit 049a15d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 13 deletions.
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ export interface Window {

export as namespace isValidThaiID;
export { isValidThaiID };
export default isValidThaiID;
export default isValidThaiID;
45 changes: 33 additions & 12 deletions src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,60 @@

/**
* Validate the Thai citizen ID.
* @param id The ID to validate.
*
* This function validates a Thai citizen ID by checking its format and calculating the checksum.
* The ID must be a string of 13 digits. If the ID is provided as a number, it will be converted to a string.
*
* @param {string | number} id - The ID to validate. It can be a string or a number.
* @returns {boolean} - Returns true if the ID is valid, otherwise false.
*
* @example
* // Valid ID
* const isValid = isValidThaiID('1112034563562'); // true
*
* @example
* // Invalid ID (wrong pattern)
* const isValid = isValidThaiID('1101700230705'); // false
*
* @example
* // Invalid ID (less than 13 characters)
* const isValid = isValidThaiID('110170023073'); // false
*
* @example
* // Invalid ID (mixed characters)
* const isValid = isValidThaiID('11017002070d3'); // false
*/
function isValidThaiID(id: string | number): boolean {
// Convert number to string if the ID is a number.
if (typeof id === 'number') {
id = id.toString()
id = id.toString();
}
// Check if the ID is a valid string of 13 digits.
if (!/^\d{13}$/.test(id)) {
return false
return false;
}

// Calculate the check sum.
let sum = 0
let sum = 0;
for (let i = 0; i < 12; i++) {
sum += Number(id[i]) * (13 - i)
sum += Number(id[i]) * (13 - i);
}
const checkSum = (11 - (sum % 11)) % 10
const checkSum = (11 - (sum % 11)) % 10;

// Check if the check sum is equal to the last digit of the ID.
return checkSum === Number(id[12])
return checkSum === Number(id[12]);
}

// Export the function.
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined' || window === undefined) {
module.exports = isValidThaiID
exports.default = isValidThaiID
exports.isValidThaiID = isValidThaiID
module.exports = isValidThaiID;
exports.default = isValidThaiID;
exports.isValidThaiID = isValidThaiID;
} else if (typeof window !== 'undefined') {
// Support legacy version of the browser.
// @ts-ignore
window.isValidThaiID = isValidThaiID
window.isValidThaiID = isValidThaiID;
} else {
// @ts-ignore
global.isValidThaiID = isValidThaiID
global.isValidThaiID = isValidThaiID;
}

0 comments on commit 049a15d

Please sign in to comment.