Hello friends, In this post you will see a code example that helps you to validate salesforce record id. This code will check for both 15 digit and 18 digits record id. So let's get started,

Validate salesforce record id using apex

In the below code, I have used regex pattern that matches the salesforce record id and return boolean value based on the matched pattern.

 public static boolean IsValidSalesforceId(String sRecordId, System.type objtype){
try{
if(Pattern.compile('[a-zA-Z0-9]{15}|[a-zA-Z0-9]{18}').matcher(sRecordId).matches()){
sObject sobj=(sObject)objtype.newInstance();
sObj.Id=sRecordId;
return true;
}
return false;
}
catch(Exception ex){
return false;
}
}
Execute the following code in developer console
 //Replace hardcoded id with your org record id
Boolean bflag=IsValidSalesforceId('0016F00002x1j7mQAA',Account.class);
System.debug('Is Valid Salesforce Id***^^ '+bflag);

Output:


Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.