Show error message in Visualforce Page

Show error message in Visualforce Page using ApexPages.addmessage

apex error message

Sometime we need to show error message on Visualforce page. We can implement this requirement by creating new instance of ApexPages.message and then adding message to Apexpages using ApexPages.addmessage. Then displaying these messages in visualforce page.

We can add 5 different types of message in Visualforce Page. In the example below, we are showing 5 input fields of account. We have added a button on visualforce page. Different type of message will be shown on visualforce page if we will keep any field blank.

Click for Demo

Error Message

Visualforce Code:

<apex:page standardController="Account" extensions="ErrorMessageInVfController">
 <apex:form >
   <apex:pageblock >
      <apex:pageMessages id="showmsg"></apex:pageMessages>
         <apex:panelGrid columns="2">
           Account Name: <apex:inputText value="{!}"/>
           Account Number: <apex:inputText value="{!acc.AccountNumber}"/>
           Account Phone: <apex:inputText value="{!}"/>
           Account Site: <apex:inputText value="{!}"/>
           Account Industry: <apex:inputText value="{!acc.industry}"/>
           <apex:commandButton value="Update" action="{!save}" style="width:90px" rerender="showmsg"/>

Apex Code:

public with sharing class ErrorMessageInVfController {
    public Account acc{get;set;}
    public ErrorMessageInVfController(ApexPages.StandardController controller) {
        acc = new Account();

    public void save(){
      if( == '' || == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please enter Account name'));

      if(acc.AccountNumber == '' || acc.AccountNumber == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter Account number'));

      if( == '' || == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please enter Account phone'));

      if( == '' || == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Please enter Account site'));

      if(acc.industry == '' || acc.industry == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Please enter Account industry'));


For more details about difference between apex:pageMessage and apex:pageMessages, refer apex:pageMessage and apex:pageMessages – Salesforce post.

Permanent link to this article: