check if a string is a salesforce id

  • 1
  • Question
  • Updated 1 year ago
Anyone have a good way to perform a check on a string to see if it is a salesforce id, beyond ensuring that it's 18 characters long?
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb

Posted 1 year ago

  • 1
Photo of Skuidward Tentacles (Raymond)

Skuidward Tentacles (Raymond), Champion

  • 17,224 Points 10k badge 2x thumb
I think the first 3 characters are the object ID, so you could check to make sure the string has 18 characters and begins with a 3 character string that matches one of the objects you are receiving these id’s from.
Photo of Mark DeSimone

Mark DeSimone, Official Rep

  • 11,050 Points 10k badge 2x thumb
Are you checking just a string itself, or is there metadata available that you could also check (checking for field type, for example)?
Photo of Matt Sones

Matt Sones, Champion

  • 31,478 Points 20k badge 2x thumb
Hmm, that might work, Raymond... but to make the solution portable between orgs I'm going to have to dynamically get the first three characters of the objects in question. Is there a simple way to do that beyond building a model on the object to query it and check the id?

Here's what I'm doing right now. It's obviously not foolproof, but should work 99% of the time for our use case.

string.length === 18 && string.match(/[A-Za-z0-9]/)