Show Error Message in Visualforce Page

In some cases, we need to show an error message or warning message on the Visualforce page. We can implement this requirement by creating a new instance of ApexPages.message and then adding the message to Apexpages using ApexPages.addmessage. Then displaying these messages in visualforce page.

There are 5 different types of message that we can show on Visualforce Page. In the example below, I am showing 5 input fields of contact and a button on the visualforce page. Different type of message will be shown on the visualforce page if we will keep any field blank.

Visualforce Page:

<apex:page standardController="Account" extensions="pageMessageErrorController">
 <apex:form >
   <apex:pageblock >
      <apex:pageMessages id="pageMessageId"></apex:pageMessages>
         <apex:panelGrid columns="2">
           Contact First Name: <apex:inputText value="{!contact.FirstName}"/>
           Contact Last Name: <apex:inputText value="{!contact.LastName}"/>
           Contact Phone: <apex:inputText value="{!}"/>
           Contact Company: <apex:inputField value="{!contact.AccountId}"/>
           Contact Email: <apex:inputText value="{!contact.Email}"/>
           <apex:commandButton value="Update" action="{!save}" style="width:90px" rerender="pageMessageId"/>

Apex Code:

public with sharing class pageMessageErrorController {
    public Contact contact{get;set;}
    public pageMessageErrorController(ApexPages.StandardController controller) {
        contact = new Contact();
    public void save(){
      if(contact.FirstName == '' || contact.FirstName == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please enter Contact First Name'));
      if(contact.LastName == '' || contact.LastName == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter Contact Last Name'));
      if( == '' || == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please enter Contact phone'));
      if(contact.AccountId == '' || contact.AccountId == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Please enter Contact Company'));
      if(contact.Email == '' || contact.Email == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Please enter Contact Email'));