How to display error message next to field in Visualforce page in Salesforce?

Sample Code:

Visualforce page:

<apex:page controller="Sample">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:inputField value="{!newAcct.Name}"/>
                <apex:inputField value="{!newAcct.Industry}"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton value="Store" action="{!insertAcct}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Controller:

public with sharing class Sample {
    
    public Account newAcct {get;set;}
    
    public Sample() {
        newAcct = new Account();
    }
    
    public PageReference insertAcct() {
        if ( newAcct.Industry == null ) {
            newAcct.Industry.addError('Please fill Industry');
            return null;
        } else {
            insert newAcct;
            PageReference pg = new PageReference('/' + newAcct.Id);
            pg.setRedirect(true);
            return pg;
        }
    }
        
}

Output:



Cheers!!!

No comments:

Post a Comment