2

I recently found that some strings, which are very much NOT Salesforce Ids, will cause instanceof Id to return a false positive.

Example:

String extId = '243209199570387970';
Boolean isId = extId instanceof Id;
System.debug(isId); // ouputs TRUE but should be false

Is this just simply a bug or is there some weird intended behavior in this? Are there any alternatives to checking if a String is a Salesforce ID?

1
  • worth noting that I mock Ids all the time using 001000000000000 or 001000000000001 for different accountIds when unit testing methods that accept sobjects as args
    – cropredy
    Commented Dec 20, 2022 at 19:20

2 Answers 2

4

Their check on instance of Id just checks if it is instance of String and the length of the String is either 15 or 18 characters and that first 15 characters contain at least one 0. It also allows to type in any symbol that cannot be used in ID, such as ;, for example. It is not a bug, but rather not expected behavior, as you can run this code without errors, too:

Id extId = '243209199570387970';
System.debug(extId); 

As a workaround you can try this:

String extId = '243209199570387970';
Boolean isId = true;
try {
    ((Id) extId).getSobjectType();
} catch (Exception e) {
    isId = false;
}
System.debug(isId); 
2
  • Not sure if this is a change with V59.0 -- we were checking Id using instance of and it was working well for us. Then it stopped working (around the time of our release to V59). When we check stripe IDs (18 characters) and they contain a 0 (zero) it evaluates to true. If it does not contain a 0 (zero) it evaluates to false. Commented Oct 18, 2023 at 20:54
  • You are right, now they are checking that in the first 15 chars there is a 0. For example, this will still return true: System.debug('243;0919957138;z71' instanceof Id); @JeffVdovjak Commented Oct 19, 2023 at 9:43
0

You can simplify the test to simply try to assign to an ID variable.

String str = '243209199570387970';
Boolean isId = true;
try {
    Id idStr = str;
} catch (Exception e) {
    isId = false;
}
System.debug(isId);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .