Validating a Salesforce Id
There are two levels of validating salesforce id:
- check format using regular expression
[a-zA-Z0-9]{15}|[a-zA-Z0-9]{18}
- for 18-characted ids you can check the the 3-character checksum:
Code examples provided in comments:
- C#
- Go
- Javascript
- Ruby
Something like this should work:
[a-zA-Z0-9]{15,18}
It was suggested that this may be more correct because it prevents Ids with lengths of 16 and 17 characters to be rejected, also we try to match against 18 char length first with 15 length as a fallback:
[a-zA-Z0-9]{18}|[a-zA-Z0-9]{15}
Just use instanceOf to check if the string is an instance of Id.
String s = '1234';
if (s instanceOf Id) System.debug('valid id');
else System.debug('invalid id');