Skip to content

Instantly share code, notes, and snippets.

@mayvazyan
Forked from knation/salesforceId.js
Last active November 5, 2021 15:05
Show Gist options
  • Save mayvazyan/138ff6c9bf6dda2518caa3df2aa2e40c to your computer and use it in GitHub Desktop.
Save mayvazyan/138ff6c9bf6dda2518caa3df2aa2e40c to your computer and use it in GitHub Desktop.
JavaScript Salesforce ID Check & Expansion
class SalesForceIdValidator {
private ID_REGEX = /^[0-9a-zA-Z]{15}([0-9a-zA-Z]{3})?$/;
private ID_EXPAND_ARRAY = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5'];
constructor(private id: string) {}
public IsValid(): boolean {
if (!this.id) {
console.warn('[SalesForceIdValidator] id is empty');
return false;
}
if (!this.ID_REGEX.test(this.id)) {
console.warn('[SalesForceIdValidator] id is invalid');
return false;
}
if (this.id.length === 18) {
if (!this._validateCheckSum()) {
console.warn('[SalesForceIdValidator] checksum is invalid');
return false;
}
}
return true;
}
private _validateCheckSum() {
return this.id.endsWith(this._getCheckSum());
}
private _getCheckSum() {
var chunks = [this.id.substr(0, 5), this.id.substr(5, 5), this.id.substr(10, 5)];
let chunkBits = ['','',''];
for (var i=0;i<chunks[0].length;i++) chunkBits[0] = (/[A-Z]/.test(chunks[0].substr(i, 1)) ? '1' : '0') + chunkBits[0];
for (var i=0;i<chunks[1].length;i++) chunkBits[1] = (/[A-Z]/.test(chunks[1].substr(i, 1)) ? '1' : '0') + chunkBits[1];
for (var i=0;i<chunks[2].length;i++) chunkBits[2] = (/[A-Z]/.test(chunks[2].substr(i, 1)) ? '1' : '0') + chunkBits[2];
const ID_EXPAND_ARRAY = this.ID_EXPAND_ARRAY;
return ID_EXPAND_ARRAY[parseInt(chunkBits[0], 2)] + ID_EXPAND_ARRAY[parseInt(chunkBits[1], 2)] + ID_EXPAND_ARRAY[parseInt(chunkBits[2], 2)];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment