Newer Version Available
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:
You need to write a custom controller like the following:
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.
1swfobject.registerObject("clippy.codeblock-0", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17<apex:page controller="MyController" tabStyle="Account">
18 <apex:messages/>
19 <apex:form>
20 <apex:pageBlock title="Hello {!$User.FirstName}!">
21 This is your new page for the {!name} controller. <br/>
22 You are viewing the {!account.name} account.<br/><br/>
23 Change Account Name: <p></p>
24 <apex:inputField value="{!account.name}"/> <p></p>
25 Change Number of Locations:
26 <apex:inputField value="{!account.NumberofLocations__c}" id="Custom_validation"/>
27 <p>(Try entering a non-numeric character here, then hit save.)</p><br/><br/>
28 <apex:commandButton action="{!save}" value="Save New Account Name"/>
29 </apex:pageBlock>
30 </apex:form>
31</apex:page>1swfobject.registerObject("clippy.codeblock-1", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class MyController {
18 Account account;
19
20 public PageReference save() {
21 try{
22 update account;
23 }
24 catch(DmlException ex){
25 ApexPages.addMessages(ex);
26 }
27 return null;
28 }
29
30 public String getName() {
31 return 'MyController';
32 }
33
34 public Account getAccount() {
35 if(account == null)
36 account = [select id, name, numberoflocations__c from Account
37 where id = :ApexPages.currentPage().getParameters().get('id')];
38 return account;
39
40 }
41}