top of page
Search

Display Custom Required Block with Custom Error Messages in VF Page

  • Writer: Oliver Jones
    Oliver Jones
  • Aug 6, 2020
  • 1 min read


Sometimes in visual force pages while using custom Apex:SelectOption or Apex:InputText tags, the attribute required = "true" won't work to enforce required field validation, in such cases, the following way is the workaround. Here displaying custom error messages like Error: You must enter a value beneath the fields also added.


Visual Force Page code:


//----------//----------//

<apex:Messages styleClass="errorMsg" />

<apex:pageBlockSection columns="1" id="cityStateBlock">

<apex:inputField list="{! cityList}" required="true" value="{! customObj.City__c}" id="CITY"/>

<apex:pageBlockSectionItem id="stateHolder">

<apex:outputLabel value="STATE" for="STA"/>

<apex:outputPanel layout="block" styleClass="requiredInput">

<apex:outputPanel layout="block" styleClass="requiredBlock"/>

<apex:selectList size="1" value="{! customObj.State__c}" id="empst">

<apex:selectOptions value="{! stateOptions}" />

</apex:selectList>

<apex:outputPanel rendered="{! stateError}">

<div class="errorMsg">

<strong>Error</strong>&nbsp;You must enter a value

</div>

</apex:outputPanel>

</apex:outputPanel>

</apex:pageBlockSectionItem>

</apex:pageBlockSection>

//----------//----------//


Apex Controller code:


//----------//----------//

public Custom_Object__c customObj { get;set; }

public Boolean stateError { get;set; }

//----------//----------//

if(customObj.State__c == Null || customObj.State__c == '') {

ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'State: You must enter a value'));

stateError = True;

return Null;

}

else {

stateError = False;

}

//----------//----------//


The custom error shows on the top of the page as shown below:




You can also customize the error message on the required field validation beneath the text box.


I hope this helps :)

 
 
 

Comments


bottom of page