+ Start a Discussion
Nisar AhmedNisar Ahmed 

How to display an custom validation error on a VF page.

Hi All,


I need to display an custom validation error message for an 'inputText' field.

For Example:

Here, I need to display an error message if the inputText for 'Name' is null or empty.


<div style="position:absolute; top: 145px; left: 30px;" class="cnt_popup">
<div style="position:absolute; top: 140px; left: 105px; height:20px; width:200px;" >
     <apex:inputText id="name" value="{!Name}" styleClass="textarea" required="true">                                    

 Please let me know if you have any idea about how to display an custom validation error message.


Shailesh DeshpandeShailesh Deshpande

Within ur class add a condition check...


if(Name == null  || Name == '')


ApexPages.addMessages(ApexPages.Severity.ERROR, ' Your Error message');



and on ur page include the apex:pageMessages tag.

Nisar AhmedNisar Ahmed

Hi Shailesh,


Thanks for your response.


Could you please let me know if have any idea about how to do the same in the page itself like by using javascript ??

Shailesh DeshpandeShailesh Deshpande

You wont be able to use ApexMessages with javascript..in that case u will need to have a hidden div or some other component, which will be visible when theres an error.



function myFN()


if(document.getlementbyId('inputtextIdforName' ) == '')


     document.getElementById('myDiv').innerHTML = 'Error';

     document.getElementById('myDiv').style.display = '';





<div id="myDiv" style="display:none">



            Below is the sample code to retrieve Custom validation error message.


Controller code:

ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Your Custom validation message');



To add this message in the visual force page.



            <apex:pageMessages ></apex:pageMessages>


If you have a validation rule already built in salesforce (not using code) and the message is set to display on a specific field instead of at the top of the page, this little trick will work if you're trying to get the same behavior on a visualforce page:


public Account A = new Account();
public Account getA(){ return A;}

public pageReference saveRecord(){ 
          upsert A; return new Pagereference('/'+A.Id); 
     catch(Exception dmle) 
           return null;                                   

 I didn't add all of the code because I didn't want to complicate it and have you miss the important part.  The try catch that adds the dmle messages to the apexPages is really the important part.  It will automatically adopt the existing custom field validation formatting.  That's it!


Great Post JPlay, this worked great.