Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Web-development
  3. Question
Web-development

How to check in Apex if a Text field is blank

Asked by Ankit Yadav Aug 1, 2021 4.4K views 2 answers
Share

About this question

 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;


Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Jun 24, 2024

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.

Was this helpful?

More Web-development discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest from the JanBask Blog

Guides, tips and career advice from JanBask experts.