Apex String Methods to Determine Character Types in Salesforce

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');
        }
    }
}

To execute the above Apex class, we need to create an instance of the class. Using that instance, we can call the method where we implemented the logic.

In the output, you can see the message that we entered in the if condition, which displays the account number that does not contain numeric values.

String Methods in Salesforce Apex

2. String.isAlpha() Method in Apex String

In Salesforce Apex, the String.isAlpha() method checks if a string consists only of alphabetic characters.

This means it returns true if all characters in the string are letters (A-Z or a-z) and false if the string contains any non-alphabetic characters (such as numbers, spaces, or symbols).

isAlpha() does not distinguish between uppercase and lowercase letters; both are treated as valid alphabetic characters.

Syntax:

Boolean isAlpha = stringVariable.isisAlpha();

Example: Use String.isAlpha() Method in Apex

Let’s take an example. We want to validate alphabetical fields while the user enters the details. We can check if the user enters any character except the alphabet.

In the Apex class below, I added the method with an account as a parameter. In the if condition, we check whether any account name contains a character or symbol other than letters. If another character is found, an exception will be thrown, and the record will not be saved.

As we are using the customException, we need to declare the class that extends the exception class.

public class StringMethod {
    public void CheckStringMethod (Account acc) {

        if (String.isEmpty (acc.Name) || !acc.Name.isAlpha()) {
            throw new CustomException (' Name must contain only alphabetic characters.');
        }                
        try {
            upsert acc;
            System.debug (' Employee record saved successfully.');
        } 
        catch (Exception e) {
            System.debug (' Error saving employee record: ' + e.getMessage());
        }
    }        
    public class CustomException extends Exception {}
}

As we execute the above code, I first enter the account name, which consists only of letters. Then, in the output, you can see the record is successfully saved.

Salesforce Apex String Method

Now, we will see if we added a number to the account name and what will happen. As I executed the code, the record was not saved because we threw an exception if the account name contained any character other than the alphabet.

String Exception in Salesforce Apex

3. String.isAlphaNumeric() Method in Apex String

In Salesforce Apex, the String.isAlphaNumeric() method is used to check whether a string contains only alphanumeric characters, which means letters (A-Z, a-z) and numbers (0-9). This method returns a Boolean value.

Syntax:

Boolean isAlphaNumeric = stringVariable.isAlphaNumeric();

Example: Use String.isAlphaNumeric() Method in Apex

In the Apex class below, we will check whether any string has an alphanumeric form. If it is there, then it will return true. Otherwise, it will return false.

public class StringMethod {
    public void CheckStringMethod() {

        String str1 = 'Hello123';
        String str2 = 'Hello World!';
        String str3 = '12345';
        
        System.debug (str1.isAlphaNumeric()); 
        System.debug (str2.isAlphaNumeric()); 
        System.debug (str3.isAlphaNumeric());        
    }
}

As I execute the code in the output, you can see the first and last strings return true because the first string is alphanumeric, and the last one has numbers.

However, the second string has a space between the two strings, which is why it returns false.

Salesforce Apex String Methods

4. String.isWhiteSpace() Method in Apex String

In Salesforce Apex, the String.isWhitespace() method checks whether a given string contains only whitespace characters. This method is useful when you want to validate if a string is either empty or consists purely of whitespace characters such as spaces, tabs, or newlines.

It returns a boolean value; if the string is empty or consists entirely of whitespace characters, it returns true, and otherwise, false.

Syntax:

Boolean isWhitespace = stringVariable.isWhitespace();

Example: Use String.isWhitespace() Method in Apex

In the Apex class below, I provided three strings and checked whether any of them contained whitespace. If any string contains entirely whitespace, then it will return true.

Here, I declared a boolean variable, which will store the result as true or false, depending on the strings.

We can also verify this using the system.assertEquals(expected output, actual output) method, which takes two parameters.

The first step is to enter the expected output, and in another parameter, we need to provide the actual output. This is basically used in the Apex test class for testing purposes.

public class StringMethod {
    public void CheckStringMethod() {

        String s1 = ' ' ;
        Boolean b1 = s1.isWhitespace();
        System.debug ('s1 contains whitespace: ' + b1);
        System.assertEquals(true, b1);
         
        String s2 = '' ;
        Boolean b2 = s2.isWhitespace();
        System.debug ('s2 contains whitespace: ' + b2);
        System.assertEquals(true, b2);
         
        String s3 = 'TSinfo 1234';
        Boolean b3 = s3.isWhitespace();
        System.debug ('s3 contains whitespace: ' + b3);
        System.assertEquals(false, b3);
    }
}

After executing the Apex class, you can see the first two strings displayed as true because these strings contain white space entirely; there is no character available. But in the third string, there is also white space available, and a character is present, so it returns false.

Apex String Methods to Determine Character Types in Salesforce

5. containsWhitespace() Method in Apex String

In Salesforce Apex, containsWhitespace() is a method in the string class that checks if a string contains any whitespace characters such as spaces, tabs, newlines, etc. This method returns a Boolean value. If the string contains at least one whitespace character, then it returns true; otherwise, it is false.

Syntax:

Boolean containsWhitespace = stringVariable.containsWhitespace();

Example: Use String.containsWhitespace() Method in Apex

Using the Apex class below, we are creating an account record, and while creating the account, we are also checking that the account name should not be empty and should not be entered without whitespace.

For that, in the if condition, we are checking for a null value, and in another if condition, we are checking if the account name does not contain whitespace. If it does, we throw an exception, and the record should not get saved. As we are using the custom exception, we must also declare an exception class.

public class StringMethod {
    public void CheckStringMethod (Account acc) {

        if (acc.Name == null) {
            throw new CustomException (' Account Name cannot be empty.');
        }

        if (!acc.Name.containsWhitespace()) {
            throw new CustomException (' Enter Full Name and it Should contain spaces.');
        }
        try {
            upsert acc;
            System.debug (' Account saved successfully: ' + acc.Name);
        } catch (DmlException e) {
            System.debug ( 'Error while saving Account: ' + e.getMessage());
            throw e;
        }
    }
    public class CustomException extends Exception {}
}

To execute the class, we need to create an Account instance and provide the account name. First, I entered the account name correctly, which contains whitespace. Then, I executed the code, and you can see the record was saved successfully.

Apex String Methods Examples

Now, I entered the account name without any whitespace between two strings and then executed the code. We got an exception that we declared in the if condition where we checked the whitespace in the string, and the record did not get saved.

Use Apex String Methods in Apex

Conclusion

I hope you have got an idea about about string methods in Apex. In this article, I have explained some string methods used to determine character types in Salesforce to ensure that the data the user is entering matches the criteria. I explained these methods with proper syntax and also explained the code using examples.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.