How to validate String as Salesforce Record Id using InstanceOf keyword?
Validate String as Salesforce Record Id Using InstanceOf Keyword
I had scenario where store multiple user in custom settings with “;” separator. Used that custom settings to skip the trigger for few scenario like data load, running batch job… Some time admin/developer will manually update customer setting with their Salesforce User record id once completed their activities(data load or running batch job) – they will manually remove their user id.
Some scenarios we will be updating that customer settings using apex code before batch job execute or running cleanup script via Developer Console.
Some of the user making mistake while removing their user id – for example:
Added user id : 005G0000001srdD;005G0000001MqdH;005G0000001QtwP
After removed their user id: 05G0000001srdD;;005G0000001QtwP
When apex code adding/removing user from custom settings – system throwing multiple error like
- Invalid Id Type
- Null pointer exception
To resolve and re-arrange the user id in above example we have used “InstanceOf” keyword in apex code.
String strUserIds = '05G0000001srdD;;005G0000001QtwP'; system.debug('Initial State : ' + strUserIds); list<String> lstUserIDsFinal = new list<String>(); list<String> lstUserIDs = strUserIds.split(';'); for(String strUsertID : lstUserIDs) { if(strUsertID InstanceOf ID) { if(!lstUserIDsFinal.contains(strUsertID)) { lstUserIDsFinal.add(strUsertID); } } } strUserIds = String.join(lstUserIDsFinal, ';'); system.debug('Final Result : ' + strUserIds);
Output: