Sub topic 6
Converting input to Id, Integer, Date and Boolean before use
This chapter assumes you can write Apex classes, static SOQL with WHERE, ORDER BY and LIMIT, and that you have seen Database.query and bind variables in the earlier chapters. Here you learn to convert user-supplied text into real Apex types before it reaches a query, and where that conversion helps and where it does not.
Why convert before you query
Input from a Lightning component, a REST endpoint, a URL parameter, or a Flow arrives as text. A value like 5 or 2026-11-30 is only a string that looks like a number or a date. If you build a query with it, the database sees whatever characters the caller sent.
Converting the string to a typed value gives you three benefits:
- Rejection of malformed input. A value that is not an Id, a whole number, a date, or a Boolean fails at the conversion step, with an error you control, instead of failing inside the query engine.
- A narrow value space. An
Integerholds only digits and an optional sign. ADateholds only a calendar date. A quote character cannot survive the conversion. - Correct binding. A typed value placed in the bind map is compared with the field using the field's own type, so no implicit coercion happens.
Typed conversion is a validation step. It does not replace bind variables. The primary defense is still to pass the typed value as a bind, as in the earlier chapter on Database.queryWithBinds.
The four conversions
| Target type | Converter | Throws on bad input | Gotcha |
|---|---|---|---|
| `Id` | `Id.valueOf(String)` | `StringException` | A well-formed Id can belong to the wrong object. Check `getSObjectType()`. |
| `Integer` | `Integer.valueOf(String)` | `TypeException` | A valid number can still be absurd, such as a negative `LIMIT`. Check a range. |
| `Date` | `Date.valueOf(String)` | `TypeException` | Expects `yyyy-MM-dd`. `Date.parse` depends on the user's locale, so avoid it for input. |
| `Boolean` | `Boolean.valueOf(String)` | Does not throw | Returns `false` for any text that is not `true`. You must check the text yourself. |
The Boolean row matters most. Boolean.valueOf('yes') and Boolean.valueOf('tru') both return false, so a typo silently flips the meaning of a filter. Write a strict parser instead.
A small parsing helper
Collect the conversions in one class so every caller applies the same rules. Each method returns null for blank input, which the caller treats as "no filter". Any other bad value throws a custom exception.
public with sharing class InputParser {
public class InputException extends Exception {}
public static Id toId(String raw, Schema.SObjectType expectedType) {
if (String.isBlank(raw)) {
return null;
}
Id parsed;
try {
parsed = Id.valueOf(raw.trim());
} catch (StringException e) {
throw new InputException('Value is not a valid record Id');
}
if (parsed.getSObjectType() != expectedType) {
throw new InputException('Id belongs to a different object');
}
return parsed;
}
public static Integer toInteger(String raw, Integer minValue, Integer maxValue) {
if (String.isBlank(raw)) {
return null;
}
Integer parsed;
try {
parsed = Integer.valueOf(raw.trim());
} catch (TypeException e) {
throw new InputException('Value is not a whole number');
}
if (parsed < minValue || parsed > maxValue) {
throw new InputException('Number must be between ' + minValue + ' and ' + maxValue);
}
return parsed;
}
public static Date toDate(String raw) {
if (String.isBlank(raw)) {
return null;
}
try {
return Date.valueOf(raw.trim());
} catch (TypeException e) {
throw new InputException('Date must use the format yyyy-MM-dd');
}
}
public static Boolean toBoolean(String raw) {
if (String.isBlank(raw)) {
return null;
}
String value = raw.trim().toLowerCase();
if (value == 'true') {
return true;
}
if (value == 'false') {
return false;
}
throw new InputException('Value must be true or false');
}
}Some details are worth noting.
- Id conversion.
Id.valueOfaccepts 15-character and 18-character forms and returns the 18-character form. CheckinggetSObjectType()stops a caller from passing a Contact Id where an Account Id is expected. - Trimming.
trim()removes accidental whitespace from copy and paste. It is not a security measure. - Integer range. The type check alone does not make a value safe to use.
LIMIT -5andLIMIT 2000000000are both legal integers and both are bad. EverytoIntegercall takes explicit bounds. - Date format.
Date.valueOfreads the fixedyyyy-MM-ddform, so the result does not depend on who is logged in.
Using typed values in a dynamic query
The next method builds a WHERE clause only from the filters the caller supplied. Every clause is a literal written in your code, and every value travels in the bind map. The caller never contributes query text.
public with sharing class OpportunitySearch {
public static List<Opportunity> search(
String accountIdText,
String minAmountText,
String closeAfterText,
String openOnlyText,
String limitText
) {
Id accountId = InputParser.toId(accountIdText, Account.SObjectType);
Integer minAmount = InputParser.toInteger(minAmountText, 0, 1000000000);
Date closeAfter = InputParser.toDate(closeAfterText);
Boolean openOnly = InputParser.toBoolean(openOnlyText);
Integer maxRows = InputParser.toInteger(limitText, 1, 200);
if (maxRows == null) {
maxRows = 50;
}
List<String> clauses = new List<String>();
Map<String, Object> binds = new Map<String, Object>{ 'maxRows' => maxRows };
if (accountId != null) {
clauses.add('AccountId = :accountId');
binds.put('accountId', accountId);
}
if (minAmount != null) {
clauses.add('Amount >= :minAmount');
binds.put('minAmount', minAmount);
}
if (closeAfter != null) {
clauses.add('CloseDate >= :closeAfter');
binds.put('closeAfter', closeAfter);
}
if (openOnly == true) {
clauses.add('IsClosed = false');
}
String soql = 'SELECT Id, Name, Amount, CloseDate FROM Opportunity';
if (!clauses.isEmpty()) {
soql += ' WHERE ' + String.join(clauses, ' AND ');
}
soql += ' ORDER BY CloseDate DESC LIMIT :maxRows';
return Database.queryWithBinds(soql, binds, AccessLevel.USER_MODE);
}
}Three points about this design:
LIMITtakes a bind. You do not need to concatenate the number.LIMIT :maxRowsworks in dynamic SOQL, and the bound value is already range-checked.- The Boolean never enters the query text. The code decides between
IsClosed = falseand no clause. A Boolean has only two values, so branching in Apex is simpler than binding it. - Blank means absent. A caller who leaves a field empty gets no filter for it. A caller who sends junk gets an
InputException.
When you must concatenate a typed value
Sometimes a value has to become query text, for example when you build a query for a layer that cannot take a bind map. A typed value converted back to a string is safe in that position, because the type guarantees the character set:
- An
Integerconverted withString.valueOfcontains only digits and a minus sign. - An
Idcontains only letters and digits. - A
Dateconverted withString.valueOfproducesyyyy-MM-dd 00:00:00, which is not a valid SOQL date literal. UseDatetime.newInstance(d, Time.newInstance(0, 0, 0, 0)).format('yyyy-MM-dd'), and remember that SOQL date literals take no quotes.
This works, but it needs more care and offers more ways to get the format wrong than a bind does. Treat it as the exception.
public static List<Opportunity> closedSince(String daysText) {
Integer days = InputParser.toInteger(daysText, 1, 3650);
if (days == null) {
days = 30;
}
// days is an Integer in 1..3650, so the concatenation cannot carry a quote or a keyword.
return Database.query(
'SELECT Id, Name FROM Opportunity WHERE CloseDate = LAST_N_DAYS:' + String.valueOf(days) + ' LIMIT 100'
);
}Common errors
- Converting after the query is built. The check must happen before any string concatenation. If you concatenate first and parse later, the parse protects nothing.
- Catching the exception and falling back to the raw string. A
catchblock that reusesrawdefeats the whole step. On failure, throw or return an error to the caller. - Using
Boolean.valueOfas a validator. It never rejects anything. Use the strict parser above. - Trusting an Id because it parses. A well-formed Id says nothing about whether the user may read that record. Sharing, CRUD, and field-level security come from
AccessLevel.USER_MODE, which the query above uses. - Treating typed conversion as a fix for text. A
NameorIndustryfilter has no numeric type to convert to. Text values must go through bind variables, and identifiers must come from an allowlist, as covered in the next chapters.
Testing the parser
Test the failure paths as carefully as the success paths. Each rejected value below is a case that would otherwise reach a query.
@IsTest
private class InputParserTest {
@IsTest
static void rejectsBadValues() {
List<String> failures = new List<String>();
try { InputParser.toInteger('5; DROP', 1, 10); } catch (InputParser.InputException e) { failures.add('int'); }
try { InputParser.toInteger('500', 1, 10); } catch (InputParser.InputException e) { failures.add('range'); }
try { InputParser.toDate('30/11/2026'); } catch (InputParser.InputException e) { failures.add('date'); }
try { InputParser.toBoolean('yes'); } catch (InputParser.InputException e) { failures.add('bool'); }
try { InputParser.toId('001xx', Account.SObjectType); } catch (InputParser.InputException e) { failures.add('id'); }
Assert.areEqual(5, failures.size(), 'Every bad value must be rejected');
}
@IsTest
static void acceptsGoodValues() {
Account a = new Account(Name = 'Acme');
insert a;
Assert.areEqual(a.Id, InputParser.toId(a.Id, Account.SObjectType));
Assert.areEqual(7, InputParser.toInteger(' 7 ', 1, 10));
Assert.areEqual(Date.newInstance(2026, 11, 30), InputParser.toDate('2026-11-30'));
Assert.areEqual(true, InputParser.toBoolean('TRUE'));
Assert.isNull(InputParser.toInteger('', 1, 10));
}
}Exercise
A REST endpoint accepts contactId and pageSize as strings and builds SELECT Id, LastName FROM Contact WHERE Id = :contactId LIMIT :pageSize. A caller sends a valid Account Id as contactId and -1 as pageSize. Which two checks from this chapter would reject these values, and what does each check do?
Show answer
First, InputParser.toId(contactIdText, Contact.SObjectType) parses the text and then compares getSObjectType() with Contact.SObjectType. The Account Id is well formed, but the object type does not match, so it throws an InputException. Second, InputParser.toInteger(pageSizeText, 1, 200) parses -1 successfully but fails the range check, so it throws an InputException. Both checks run before the query, and the surviving typed values go into the bind map.
Exercise
Why does Boolean.valueOf(openOnlyText) fail as input validation, and how does the strict parser in this chapter fix it?
Show answer
Boolean.valueOf returns false for any text that is not true, so a typo such as tru or yes is accepted and silently flips the filter. The strict parser lowercases and trims the text, accepts only true or false, and throws an InputException for everything else. Blank input returns null, which the caller treats as "no filter".