Validating an Id

Source code:

Problem

Many developers try to validate an Id by trying to convert a string to type Id and catching an exception. There is a more elegant way of doing it.

Solution

This method validates an Id's length(15 or 18) and validates the possible characters that should exist within an Id using regular expressions. The first step escapes any possible single quotes to do two things: validate that the given string is a valid Id and that it is not an unauthorized parameter from the URL.

[code apex] static public String validateId(String Idparam) { String id = String.escapeSingleQuotes(Idparam); if((id.length() == 15 || id.length() == 18) && Pattern.matches('^[a-zA-Z0-9]*$', id)) { return id; } return null; } [/code]