Skip to content

Instantly share code, notes, and snippets.

@step307
Last active February 2, 2024 15:30
Show Gist options
  • Save step307/3d265b7c7cb4eccdf0cf55a68c9cfefa to your computer and use it in GitHub Desktop.
Save step307/3d265b7c7cb4eccdf0cf55a68c9cfefa to your computer and use it in GitHub Desktop.
Javascript check salesforce id validity
function isValidSfId(str) {
// https://stackoverflow.com/a/29299786/1333724
if (typeof str !== 'string' || str.length !== 18) {
return false;
}
let upperCaseToBit = (char) => char.match(/[A-Z]/) ? '1' : '0';
let binaryToSymbol = (digit) => digit <= 25 ? String.fromCharCode(digit + 65) : String.fromCharCode(digit - 26 + 48);
let parts = [
str.slice(0,5).split("").reverse().map(upperCaseToBit).join(""),
str.slice(5,10).split("").reverse().map(upperCaseToBit).join(""),
str.slice(10,15).split("").reverse().map(upperCaseToBit).join(""),
];
let check = parts.map(str => binaryToSymbol(parseInt(str, 2))).join("");
return check === str.slice(-3);
}
@LoganTann
Copy link

Suggestions :

  • add support for ids of 15 characters
  • maybe add condition typeof str === "string"
  • line 4 needs semicolon at end of line

@step307
Copy link
Author

step307 commented Aug 11, 2022

Thanks @LoganTann ! I've implemented couple of your suggestions. Not sure about 15 characters Ids because the function check the checksum and this seems to be the part of 18 characters Ids only.

@CGastrell
Copy link

Organization IDs are mostly 15 characters, and is one of the most important IDs to validate? Is there any way to do that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment