Environment (JDeveloper 11.1.1.5.0, ADF BC, ADF Faces, hr schema)
ADF Faces provides several validation types; UI component attributes validation, default ADF Faces validators, and custom ADF Faces validators. The last type (custom ADF Faces validators) enables you to create your own validation logic in a Java class then you can use it as a validator to your UI component. The custom validator can be created for a specific component in a single page, or can be created to be used in all pages in your application. In this example, I will explain how to build your own custom validator that can be used in all pages. This example based on hr schema, mainly on Employees table, and assumed that you already have built your BC. Our business rule is that the PHONE_NUMBER attribute should be at least 9 digits. The steps to build your own validator are:
- Create a Java class that implements the javax.faces.validator.Validator
interface in your viewController project as shown below. In the name field enter “PhoneValidator”, enter your desired package, and in the Optional Attributes section click the green plus symbol to add the interface that this class should implement. - After you have created the class, you will see the validate method to implement the interface. override this method as shown below.
public void validate(FacesContext facesContext,
UIComponent uIComponent,
Object object)
throws ValidatorException {
//add your validation logic here
String phone = object.toString();
if (phone.length() < 9) {
FacesMessage fm =
new FacesMessage(“Phone number should be at least 9 digits”);
throw new ValidatorException(fm);
}
}
- Now you need to register your validator in faces-config.xmlfile, locate this file in your viewController project then double click on it, after the file was opened in your main window click the overview tab, then select the validator link from the left hand side. Click on the green plus symbol to add your validator as shown below.
- Now our validator is ready to use, create a page, drag and drop the EmployeeView1 from the data control, and select ADF form from the menu.
- Right click on the PhoneNumbe filed, and select insert inside Input Text → JSF Core → Validator. Once you add the validator, go to the property inspector palette, select the ValidatorId property then select our PhoneValidator from the list. your page source should look like this source snapshot.
<af:inputText value=”#{bindings.PhoneNumber.inputValue}”
label=”#{bindings.PhoneNumber.hints.label}”
required=”#{bindings.PhoneNumber.hints.mandatory}”
columns=”#{bindings.PhoneNumber.hints.displayWidth}”
shortDesc=”#{bindings.PhoneNumber.hints.tooltip}”
id=”it4″>
<f:validator binding=”#{bindings.PhoneNumber.validator}”/>
<f:validator validatorId=”phonevalidator”/>
</af:inputText> - Run your page and enter a phone number less than 9 digits, submit the form, the error message will be shown as below.
see also: Add business rule in the setter method of an entity attribute