How to check in Apex if a Text field is blank

2.2K    Asked by Ankityadav in Web-development , Asked on Aug 1, 2021

 I'm unsure what's the shortest and most robust way to check if string is null, whether a Text field is blank / empty?

/*1*/ Boolean isBlank = record.txt_Field__c == ''; /*2*/ Boolean isBlank = record.txt_Field__c == null; /*3*/ Boolean isBlank = record.txt_Field__c.trim() == ''; /*4*/ Boolean isBlank = record.txt_Field__c.size() == 0;


Answered by Victoria Martin

 I use the isBlank(String) method on the string class in order to check if string is null

, white space or empty.

  String.isBlank(record.txt_Field__c);

The documentation says:

Returns true if the specified String is white space, empty (''), or null; otherwise, returns false.



Your Answer

Answer (1)

In Apex, you can check if a text field (String variable) is blank using a simple conditional check. Here's how you can do it:

  String textField = 'Some value'; // Replace 'Some value' with your actual text field variableif (String.isBlank(textField)) {    System.debug('The text field is blank or null.');} else {    System.debug('The text field is not blank. It contains: ' + textField);}

Explanation of the code:

String.isBlank(textField): This is a static method in the String class provided by Apex. It returns true if the specified string is null, is empty (''), or consists only of whitespace characters.

In the example:

If textField is empty (''), null, or contains only whitespace characters, String.isBlank(textField) will return true.

If textField has any non-whitespace characters, String.isBlank(textField) will return false.

Based on the result of String.isBlank(textField), you can perform different actions in your Apex code.

Example Usage:

  String textField = ''; // Empty stringif (String.isBlank(textField)) {    System.debug('The text field is blank or null.');} else {    System.debug('The text field is not blank. It contains: ' + textField);}

Output:

  DEBUG|The text field is blank or null.String textField = 'Hello World'; // Non-empty stringif (String.isBlank(textField)) {    System.debug('The text field is blank or null.');} else {    System.debug('The text field is not blank. It contains: ' + textField);}

Output:

DEBUG|The text field is not blank. It contains: Hello World

This approach allows you to effectively determine if a text field is empty or contains meaningful data, enabling you to handle your business logic accordingly in Apex.

6 Months

Interviews

Parent Categories