Newer Version Available

This content describes an older version of this product. View Latest

Validation Rules and Custom Controllers

If a user enters data on a Visualforce page that uses a custom controller, and that data causes a validation rule error, the error can be displayed on the Visualforce page. Like a page that uses a standard controller, if the validation rule error location is a field associated with an <apex:inputField> component, the error displays there. If the validation rule error location is set to the top of the page, use the <apex:messages> component within the <apex:page> to display the error. However, to get the information to the page, the custom controller must catch the exception.

For example, suppose you have the following page:
1<apex:page controller="MyController" tabStyle="Account">
2  <apex:messages/>
3  <apex:form>
4   <apex:pageBlock title="Hello {!$User.FirstName}!">
5     This is your new page for the {!name} controller. <br/>
6     You are viewing the {!account.name} account.<br/><br/>
7     Change Account Name: <p></p>
8     <apex:inputField value="{!account.name}"/> <p></p>
9     Change Number of Locations:
10     <apex:inputField value="{!account.NumberofLocations__c}" id="Custom_validation"/> 
11         <p>(Try entering a non-numeric character here, then hit save.)</p><br/><br/>
12     <apex:commandButton action="{!save}" value="Save New Account Name"/>
13   </apex:pageBlock>
14  </apex:form>
15</apex:page>

The ID of a valid account record must be specified as a query parameter in the URL for this page to render. For example, http://MyDomainName.salesforce.com/apex/myValidationPage?id=001x000xxx3Jsxb.

Note

You need to write a custom controller like the following:
1public class MyController {
2  Account account;
3
4  public PageReference save() {
5    try{
6        update account;
7       }
8    catch(DmlException ex){
9        ApexPages.addMessages(ex);
10       }
11    return null;
12  }
13
14  public String getName() {
15    return 'MyController';
16  }
17
18  public Account getAccount() {
19    if(account == null)
20      account = [select id, name, numberoflocations__c from Account
21        where id = :ApexPages.currentPage().getParameters().get('id')];
22      return account;
23
24  }
25}
When the user saves the page, if a validation error is triggered, the exception is caught and displayed on the page as they are for a standard controller.