In this Salesforce Apex tutorial, we will learn about some Apex string methods to determine character types in Salesforce, ensuring that the data the user enters matches the criteria.
Apex String Methods to Determine Character Types in Salesforce
In Salesforce, Apex string methods are used to determine the character types, such as letters, digits, and whitespace, because these methods validate and format data within strings.
When working with input, such as users entering data from UI, it’s very important to ensure that the information they are entering meets certain criteria, such as being all numeric, alphanumeric, or containing only specific symbols.
Below, I have explained some apex string methods to determine character types in Salesforce.
1. String.isNumeric() Method in Apex String
In Salesforce Apex, String.isNumeric() is a boolean method that determines whether the declared string contains only numeric characters.
- True: It returns true if all characters in the string are digits from 0 to 9.
- False: It returns false if any character from the string is non-numeric, whitespace, a letter, or a special character.
Syntax:
Boolean isNumeric = stringVariable.isNumeric();
Example: Use String.isNumeric() Method in Apex
In the Apex code below, I have explained how to use String.isNumeric() method to validate the numeric character in the string.
I created a class with a method that used the isNumeric() method to check whether the account number the user is entering only contains numeric values, using an if condition.
public class StringMethod {
public void CheckStringMethod() {
String accNo = '10001';
String accNo1 = 'A 10001';
String accNo2 = '+ 10 - 01';
if (!accNo.isNumeric()) {
system.debug ( accNo + ' Should Contain Only Numeric Value');
}
else{
System.debug (accNo + ' Variable Contains Numeric Value');
}
if (!accNo1.isNumeric()) {
system.debug (accNo1 + ' Should Contain Only Numeric Value');
}
if (!accNo2.isNumeric()) {
system.debug (accNo2 + ' Should Contain Only Numeric Value');
}
else{
System.debug ('Account Number is Numeric Value');
}
}
}