Validation Framework

Introduction

The OpenFaces validation framework is designed to compensate for lack of explicit and full support for client-side validation in JSF. In essence, it shifts the server-side validation logic of standard JSF validators to the client side.

Key Features

Benefits

In the standard JSF validation routine, user-entered data is validated on the server side by the validators and converters assigned to an input field. If either fails, the page is re-rendered back to the client to display validation errors to the user. The OpenFaces validation framework allows you to validate data on the client side before a page with invalid data is submitted, thus, minimizing server round-trips and enhancing user experience. With almost zero configuration, you can shift the standard JSF validation to the client side, preserving both logic and visual presentation of validation errors.

The OpenFaces validation framework allows you to customize presentation of validation errors. Instead of using simple labels as standard HTMLMessage(s) do, with OpenFaces, you can change a CSS of the input component with an invalid value or show a special "error" icon over the component.

There is no need to track all the validation checks and ensure there is an appropriate component to display the error. The OpenFaces validation framework provides default validation presentation for both client-side and server-side validation. If validation fails, you can be sure this will be displayed on the page.

To cover various validation scenarios, the OpenFaces validation framework allows you to choose which components to validate and when to validate them.

Getting Started with Client-Side Validation

An existing JSF application can be configured to perform all input data validation on the client side in these simple steps:

1. Attach the OpenFaces library to your project by following the instructions in the Installation section.

2. Set the application-scope context parameter org.openfaces.validation.clientValidation to "onSubmit" in web.xml. This instructs the OpenFaces validation framework to use client-side validation for the whole application.

<web-app>
...
<context-param>
    <param-name>org.openfaces.validation.clientValidation</param-name>
    <param-value>onSubmit</param-value>
</context-param>
...
</web-app>

As a result, client-side validation will be triggered before any form submission. In case of a validation error, a corresponding message will be displayed just like it is for server-side validation, but without any round-trips to the server.

Furthermore, you can configure client-side validation in a fine-grained way on a form and component level, use alternative ways of error presentation for failed validation, add OpenFaces validators, and customize validation messages.

How the Validation Framework Works

When client-side validation is turned on for a specific set of components, the components become ready to be validated on the client side. The validation process can be initiated in two ways: "automatic" - when all the components are validated before page submission, and "on demand" - when validation is invoked manually by the developer, from JavaScript code.

The set of components to be validated, the logic for automatic validation triggering, and error messages can be additionally configured to suit the logic of the most sophisticated pages.

The basics of the OpenFaces validation framework can be summarized as follows:

  • A client-side validator is added for each validator and converter from the supported set. The set of affected components is determined based on the application-wide, form-wide and per-component configuration.

    Note
    Configuration settings are applied hierarchically. That is, the component-level validation configuration takes precedence over form-wide settings, while form-wide configuration prevails over application-wide settings.

  • The OpenFaces validation framework automatically changes rendering of the standard HTML Message and Messages components so that they are able to display messages of client-side validation. You can also configure OpenFaces-specific validation presentation to show validation errors to the user. If no component to display validation errors is found, the default validation error presentation (FloatingIconMessage) is automatically used.
  • Depending on the settings of the application-wide, form-wide and per-component configuration, client-side validation can be automatically triggered before every page submission ("onSubmit" value). It can also be configured ("onDemand" value) so that it becomes the responsibility of a developer to trigger validation from JavaScript by using the Client-Side API. Individual components can be excluded from automatic on-submit validation.

    Note
    The logic of a client-side validator is equivalent to the corresponding server-side validator or converter. That is, if validation is passed for a given component on the client side, the validation and conversion will pass on the server side for this component, too.

  • If a validator fails during component validation, a corresponding message is displayed by the available validation presentation component. The page is submitted only if all the validators pass successfully; otherwise, the page submission is blocked.

Configuring Components for Client-Side Validation

There are three levels on which server-to-client validator porting can be configured: application-wide, form-wide, and per-component. Note that lower-level configuration settings take precedence. If validation is not configured on some level, it defaults to the higher-level configuration.

Application-wide

Configured by the org.openfaces.validation.clientValidation application-scope context parameter in web.xml. For more information, see the section Application Settings .

These settings affect all the components on all pages within the application. You may want to fine-tune validation settings for specific pages by using form-wide and per-component settings.

Note
It is possible to submit a form without validation (see the section Client-Side API) and exclude a particular component from the validation lifecycle (see the section Component Attributes)

Form-wide

Configured by adding the ClientValidationSupport component to the form. For more information, see the section ClientValidationSupport Component.

Affected are the components within the form to which the ClientValidationSupport component is added. This allows you to specify form-specific client-side validation configuration.

Per-component

Configured by specifying the component attributes. See the section Component Attributes.

Only the component is affected. Can be used to exclude the component from validation.

Supported Validators and Converters

On the client side, the OpenFaces validation framework supports all the OpenFaces Validators as well as the following standard JSF validators:

Name Tag
Required value No special tag, the required attribute equals to "true" for an input component.
Double Range Validator <f:validateDoubleRange>
Long Range Validator <f:validateLongRange>
Length Validator <f:validateLength>

The following standard JSF converters are supported:

Name Tag
Integer Converter
Double Converter  
Byte Converter  
Short Converter  
Float Converter  
DateTime Converter <f:convertDateTime>
Number Converter <f:convertNumber>

Note
In the current version, the ConvertDateTime component can validate dates on the client side only in the English locale format.


We are continuously extending the set of supported validators. Please let us know if you feel that other validators or converters should be supported by the OpenFaces validation framework.

Configuring Validation Error Presentation

The OpenFaces validation framework provides an alternative way to present validation messages to the user: by using the FloatingIconMessage component. It displays an image over an invalid component and applies a CSS style to it . See FloatingIconMessage for details. This kind of error messaging does not affect the page layout and, therefore, can be used as default validation error presentation. That is, when no standard HTML messages are found to display a client-client validation message, the FloatingIconMessage is automatically added to the component.

If there are no components to present validation messages to the user, all validation messages are displayed with the FloatingIconMessage component. This feature is turned on even if there is no client-side validation. You can specify whether to use default validation presentation or not by using the org.openfaces.validation.useDefaultServerPresentation and org.openfaces.validation.useDefaultClientPresentation application context parameters. These parameters should be specified in web.xml and by default are set to "true" (for more details, see the Application Settings section). These parameters also can be used for a certain form. To define whether or not to use default validation presentation for the form, you should specify the useDefaultServerValidationPresentation and useDefaultClientValidationPresentation attributes for the ClientValidationSupport component (for more details, see the ClientValidationSupport Component section).

By default, validation messages in the entire application are displayed with the FloatingIconMessage component. You can specify a different component for default validation presentation with the org.openfaces.validation.defaultPresentationClass application context parameter. In this parameter, you should define a fully-qualified class name of the component that will be used for default validation presentation and that extends the UIMessage class. For more details, see the Application Settings section.

You can also specify a component for default validation presentation for a particular form. In this case, you should define the component which is used for default presentation as a child tag for the ClientValidationSupport component (for more details, see the ClientValidationSupport Component section).

Customizing Validation Messages

Validation messages used by client-side validators and converters are the same as for the corresponding server-side validators. The messages used by OpenFaces validators can be configured either by message resource bundles , just like for standard JSF validators or as attributes of the validator tags. See the section Configuring Validator Messages for more details.

For the OpenFaces validators, you can define the summary and detail messages in place, as the corresponding validator attributes. For example:

<o:validateCustom clientFunction="return value.length>0;"
                   detail="field with id = \{0\} is required"
                   summary="validation error" />

Default validator messages of the OpenFaces validators are listed below:

Validator ID Default messages
org.openfaces.Custom summary = Validation Error; detail = validation error in input '' {0}''
org.openfaces.RegularExpression summary = Regex Validator Error; detail = '' {0}'': does not match regex
org.openfaces.EMail summary = E-mail Validator Error; detail = '' {0}'': not a valid e-mail
org.openfaces.URL summary = URL Validator Error; detail = '' {0}'': not a valid URL
org.openfaces.Equal summary = Equal Validator Error; detail = '' {0}'' must be equal to the '' {1}'' (where {1} is the client id of the second input

Validation Triggering

When client-side validation is triggered for a specific set of components, all validators attached to these components are evaluated. If any validator fails, the failed validation results are shown using the available messages component.

Client-side validation can be triggered in one of the following ways:

  • Automatic (the clientValidation attribute is set to "onSubmit") - Validation is triggered before any form submission. All the components on the form that have client-side validators are validated. If validation fails, the form is not submitted. You can submit a form without triggering the client-side validation by using the O$.submitWithoutValidation() function (see the section Client-Side API for more details). You can also exclude a particular component from automatic validation by setting the clientValidation attribute to "onDemand".
  • Manual (the clientValidation attribute is set to "onDemand") - Validation is triggered from JavaScript code by using the validation Client-Side API. This way you can validate individual components or all the components on a form. You can use manual validation triggering whenever you want, no matter what other configuration is, provided that client-side validators are assigned to the components.

Validated Components Set

The client-side validators are assigned to a component, if all of the following conditions are true:

  • Client-side validation is turned on for the component at the Per-component, Form-wide or Application-wide levels and is not turned off at lower levels.
  • The component is laid out on a form.
  • The component implements the javax.faces.component.EditableValueHolder interface.
  • The component's rendered attribute equals "true" in the render response phase (so it is actually rendered).

See the section Client-Side Component Value for the description of how the validated value is retrieved for the component.

OpenFaces Validation Framework API

Application Settings


The org.openfaces.validation.clientValidation application-scope context parameter in web.xml file specifies the application-wide settings of the OpenFaces validation framework.

Values Description
off Client-side validation is turned off for the application. This is the default value.
onDemand Client-side validation is turned on for all the components within the application, but it is not triggered automatically. Client-Side API should be used to trigger validation.
onSubmit Client-side validation is turned on for all the components within the application, and it is triggered automatically before each form submission.

The application-wide settings can be overridden on the form-wide and per-component levels.

<web-app>
...
<context-param>
    <param-name>org.openfaces.validation.clientValidation</param-name>
    <param-value>onSubmit</param-value>
</context-param>
...
</web-app>


The org.openfaces.validation.useDefaultClientPresentation application-scope context parameter in web.xml file specifies whether validatable components use the default presentation if no validation or conversion error presentation is set for these components. This property is relevant when client-side validation is turned on for the application.

Type: boolean

Values:

Values Description
true Default client-side validation presentation is turned on for all the components that don't have their own presentations (like <h:message>).
false Default client-side validation presentation is turned off for all the components that don't have their own presentations. Yet, if client-side validation is turned on, the components will be validated without any presentation.

Default value: "true"

The application-wide settings can be overridden at the form-wide and per-component levels.

<context-param>
    <param-name>org.openfaces.validation.useDefaultClientPresentation</param-name>
    <param-value>true</param-value>
</context-param>


The org.openfaces.validation.useDefaultServerPresentation application-scope context parameter in web.xml file specifies whether validatable components use the default presentation if no validation or conversion error presentation is set for these components or not. This property is relevant when client-side validation is turned off for the application.

Type: boolean

Values:

Values Description
true Default server-side validation presentation is turned on for all the components that do not have their own presentations (like <h:message>).
false No default server-side validation presentation is provided, like it would without OpenFaces.

Default value: "true"

The application-wide settings can be overridden at the form and component levels.

<context-param>
    <param-name>org.openfaces.validation.useDefaultServerPresentation</param-name>
    <param-value>true</param-value>
</context-param>


The org.openfaces.validation.defaultPresentationClass application-scope context parameter in web.xml file specifies a fully-qualified class name of the component that will be used for the default validation presentation component. The component should extend the UIMessage class. If this parameter is omitted, the FloatingIconMessage is used as a default validation presentation component.
Parameters for the validation presentation component are specified as application-scope context parameters in the web.xml file with the name in the form: <component class name without package>.<attribute name>. For example:

<!-- DEFAULT VALIDATION PRESENTATION CLASS PARAMETER -->
<context-param>
    <param-name>org.openfaces.validation.defaultPresentationClass</param-name>
    <param-value>org.openfaces.component.validation.FloatingIconMessage</param-value>
</context-param>

<!-- DEFAULT VALIDATION PRESENTATION COMPONENT ATTRIBUTES CONFIGURATION -->
<context-param>
    <param-name>FloatingIconMessage.style</param-name>
    <param-value>background: red;</param-value>
</context-param>

ClientValidationSupport Component

The ClientValidationSupport component provides configuration of client-side validation for the enclosing form.

Tag: <o:clientValidationSupport>

Example :

<form id="form1>
...
    <o:clientValidationSupport
            clientValidation="onSubmit"
            useDefaultClientValidationPresentation="true"
            useDefaultServerValidationPresentation="true">
        <o:floatingIconMessage showDetail="true" showSummary="true" style="background: red;"/>
    </o:clientValidationSupport>
...
</form>

The ClientValidationSupport component can contain the default validation presentation component as a child defined inside. In this case, the defined presentation component will override the application's defaultValidationPresentationClass component and will be used for the enclosing form to display validation or conversion errors.
Restrictions: It should be placed between the <form> and </form> tags.

Attributes:

Attribute name Type EL support Default value Description
clientValidation ClientValidationEnum yes see the corresponding application property "off" means client-side validation is turned off for the components within a form.
"onDemand" means client-side validation is turned on for the enclosing form, but it will not be automatically triggered. Client-Side API should be used to trigger client-side validation.
"onSubmit" means client-side validation is turned on for the enclosing form and it is automatically triggered on any form submission.
useDefaultClientValidationPresentation Boolean yes see the corresponding application property "true" means that in case no validation presentation component is found to display results of the client validation, the default validation presentation component is automatically added to each component with a client-side validator.
"false" means that no presentation will be provided for components without any validation presentation components defined. Yet, client-side validation will trigger for these components.
useDefaultServerValidationPresentation Boolean yes see the corresponding application property "true" means that in case no validation presentation component is found to display results of the server-side validation, the default validation presentation component is automatically added to each component with a server-side validator.
"false" means that no presentation will be provided for components without any validation presentation components defined. Yet, server-side validation will trigger for these components.

Component Attributes

To manually enable client-side validation for an individual component, you can use the clientValidation attribute by adding it to the component with the standard <f:attribute> nested tag. This attribute is of org.openfaces.renderkit.validation.validator.ClientValidationEnum type and accepts the following values:

  • "off" - The component is excluded from the validation process, no matter how the validation is configured at the application-wide and form-wide levels.
  • "onDemand" - Client-side validation is turned on for the component, but the component is excluded from the validation on automatic validation triggering before the form submission. Client-Side API should be used to trigger validation explicitly for the component.
  • "onSubmit" - Client-side validation is turned on for the component and it is validated automatically before the form submission.
<h:inputText id="testInput" required="true" value="#{Bean.value}">
    <f:attribute name="clientValidation" value="onDemand"/>
 </h:inputText>

Validation Error Message Component

The OpenFaces validation framework provides an alternative way to present validation messages by using the FloatingIconMessage component.

FloatingIconMessage

Tag: <o:floatingIconMessage>

The FloatingIconMessage component allows you to display a validation error of a validated component by changing its appearance and adding a floating icon over the component. A FloatingIconMessage does not change the page layout, so it can be added safely without raising any problems with the layout change. The validation error description will be shown through a standard HTML title attribute for the invalid component and floating icon .

FloatingIconMessage is the default presentation component for failed validation if no application-wide defaultValidationPresentationClass parameter is specified or the ClientValidationSupport component doesn't have the default presentation component declaration. This means that if no messages are configured for a component and no application- or form-wide validation presentation component is defined, the FloatingIconMessage will be automatically added for every component with client-side validators.

Example:

<form id="form1">
...
    <h:inputText id="requiredInput" required="true"/>
    <o:floatingIconMessage for="requiredInput" style="border: 2px solid red;"/>
...
</form>

Specific attributes:

Attribute name Type EL support Default value Description
for String yes required attribute The id of the validated component. This attribute is required.
id String no   The component identifier. This value must be unique within the closest parent component that is a named container.
showDetail boolean yes true Flag indicating whether the "detail" portion of displayed messages should be included in the description of the error.
showSummary boolean yes false Flag indicating whether the "summary" portion of displayed messages should be included in the description of the error.
imageUrl String yes URL to OpenFaces default icon message URL to the image file that will be used to render the icon near the component in case of failed validation.
offsetTop int yes -4 Vertical offset of the icon from the top of the invalid component.
offsetLeft int yes -4 Horizontal offset of the icon from the leftmost side of the invalid component.
noImage Boolean yes null If set to "true", the icon will not be used over the invalid component. Only the component's style will be changed. The validation message will be assigned to the component's title attribute.
noStyle Boolean yes null If set to "true", no additional styles will be applied to the components to show the validation error.
style String yes "background: #F8D3D4;" Standard CSS style string with properties for presenting the component in case of failed validation.
styleClass String yes null Standard CSS class that will be applied to the component in case of failed validation. The class will be applied to the component in addition to its existing CSS style classes.
binding FloatingIconMessage only EL null ValueExpression linking this component to a property in a backing bean.

Client-Side Component Value

The value of the component to validate during client-side validation is retrieved during validation triggering by following these rules:

  • If the component is represented by the element which tag name is "input", the component.value property is used as a value.
  • If the component is represented by the element which tag name is "checkbox" or "radio", the value is true if the component is checked and false otherwise.
  • If the component is represented by the element which tag name is "select" and the component type is "select-one", the collection of options will be obtained and the value of a selected option will be treated as the component value. So if there is no selected option, the value will be an empty string.
  • If the component is represented by the element which tag name is "select" and the component type is "select-many", the collection of options will be obtained and the array of selected options will be treated as the component value. If there is no selected option, the value will be an empty string. If there is only one selected option, the array with the one element will be used as the component value.
  • In all other cases, the component is treated as a container which accommodates other input elements. In the current version, only a group of the elements which can be checked is processed. For example, if the component is a layout table with radio buttons, the value of a selected radio button will be used as the value of the whole component.

You can specify the value to be validated by client-side validation by providing a custom JavaScript function that will be called each time the framework needs to get the component value. You should provide a JavaScript code snippet returning the value of the component by using a standard <f:attribute> nested tag with the name clientValueFunction.

In the example below, the value of the component 'test1' will be returned as the value of the component 'test2' during the client-side validation. .

<form id="testForm">
  ...
  <h:inputText id="test1"/>
  <h:inputText id="test2" >
    <f:attribute name="clientValueFunction"
     value="return
        document.getElementById('testForm:test1').value;" />
  </h:inputText>
  ...
</form>

Client-Side API

The OpenFaces validation framework provides the following client-side functions that can be called from JavaScript.

validate

Function: O$.validate(component)

Triggers all present client-side validators for the component represented by the DOM node which is specified in the component parameter. The value of the component is determined as described in the section Client-Side Component Value. Client-side validators corresponding to the server-side converters will be processed before other validators. If a converter-corresponding validator considers the value invalid, the following validators will not be processed, and only the conversion error message will be shown.

Parameters
component - A DOM node representing the component to validate.

Return value - boolean, "true" if the component value is valid, "false" - otherwise.

<form id="testForm">
  ...
  <h:inputText id="requiredInput"
               required="true"
               onchange="O$.validate(this);"/>
  <o:floatingIconMessage for="requiredInput"
                         style="border: 2px solid red;"/>
  ...
</form>
validateById

Function: O$.validateById(component_id)

Triggers all present client-side validators for the component with the id specified in the component_id parameter. It is equivalent to finding the component by id and then invoking the O$.validate(component) function.

Parameters
component_id - String. A client-side JSF component's id that will be used to retrieve the DOM node representing the component on the client side. The DOM node will be validated .

Return value - boolean. "true" if the component value is valid, "false" - otherwise.

<form id="testForm">
  ...
  <h:inputText id="requiredInput" required="true" />
  <o:floatingIconMessage for="requiredInput"
                         style="border: 2px solid red;"/>
  <h:commandButton action="#{Bean.action}"
                   onclick="O$.validateById('testForm:requiredInput');"/>
  ...
</form>
validateForm

Function: O$.validateForm(form)

Triggers all present client-side validators for all the components within the form specified in the form parameter. It is equivalent to invoking the O$.validate(component) function for all the components within a form. In the current version, validation is triggered for all the components rendered on the server side and included into the response. If on the client side, the visible property is set to "false", the validation will be triggered anyway.

Parameters
form - A DOM node representing the form to validate.

Return value - boolean. "true" if all components within a specified form are valid, "false" - if there is even one invalid component within a form.

<form id="testForm">
  ...
  <h:inputText id="requiredInput" required="true" />
  <o:floatingIconMessage for="requiredInput"
                         style="border: 2px solid red;"/>
  <h:commandButton action="#{Bean.action}"
     onclick="O$.validateForm(document.getElementById('testForm'));"/>
  ...
</form>
validateFormById

Function: O$.validateFormById(form_id)

Triggers all present client-side validators for all the components within the form whose id is specified in the form_id parameter. It is equivalent to invoking the O$.validate(component) function for all the components within the form.

Parameters
form_id - String. A client-side JSF form component's id that will be used to retrieve the DOM representing the form on the client side. This form will be validated.

Return value - boolean. "true" if all components within a specified form are valid, "false" - if there is even one invalid component within a form.

<form id="testForm">
  ...
  <h:inputText id="requiredInput" required="true" />
  <o:floatingIconMessage for="requiredInput"
                         style="border: 2px solid red;"/>
  <h:commandButton action="#{Bean.action}"
                   onclick="O$.validateFormById('testForm');"/>
  ...
</form>
validateEnclosingForm

Function: O$.validateEnclosingForm(component)

Triggers all present client-side validators for all the components within the form containing the component specified in the component parameter. It is equivalent to invoking the O$.validate(component) function for all the components within the form.

Parameters
component - A DOM node representing the component whose parent form is validated.

Return value - boolean. "true" if all components within the form to which the specified component belongs are valid, "false" - if there is even one invalid component within the form.

<form id="testForm">
  ...
  <h:inputText id="requiredInput" required="true" />
  <o:floatingIconMessage for="requiredInput"
                         style="border: 2px solid red;"/>
  <h:commandButton action="#{Bean.action}"
                   onclick="O$.validateEnclosingForm(this);"/>
  ...
</form>
submitWithoutValidation

Function: O$.submitWithoutValidation(component)

Submits the form containing the component specified in the component parameter by skipping client-side validation triggering.

Parameters
component - A DOM node representing the component whose form is submitted.

<form id="testForm">
...
    <h:inputText id="requiredInput" required="true" />
    <o:floatingIconMessage for="requiredInput" style="border: 2px solid red;"/>
    <h:commandButton action="#{Bean.action}"
                     onclick="O$.submitWithoutValidation(this);"/>
...
</form>
resetFormValidation

Function: O$.resetFormValidation(form)

Resets all client-side validators and clears validation messages for all the input components within the form specified in the form parameter.

Parameters
form - A DOM node representing the form to reset validation.

<form id="testForm">
  ...
  <h:inputText id="requiredInput" required="true" />
  <o:floatingIconMessage for="requiredInput"
                         style="border: 2px solid red;"/>
  <h:commandButton value="Cancel" action="back"
     onclick="O$.resetFormValidation(document.getElementById('testForm'));"/>
  ...
</form>
resetFormValidationById

Function: O$.resetFormValidationById(formId)

Resets all client-side validators and clears validation messages for all the input components within the form whose id is specified in the form_id parameter.

Parameters
form_id - String. A client-side JSF form component's id that will be used to retrieve the DOM representing the form on the client side. The validation will be reset for this form.

<form id="testForm">
  ...
  <h:inputText id="requiredInput" required="true" />
  <o:floatingIconMessage for="requiredInput"
                         style="border: 2px solid red;"/>
  <h:commandButton action="back" value="Cancel"
                   onclick="O$.resetFormValidationById('testForm');"/>
  ...
</form>
resetEnclosingFormValidation

Function: O$.resetEnclosingFormValidation(element)

Resets all client-side validators and clears validation messages for all the input components within the form containing the component specified in the component parameter.

Parameters
component - A DOM node representing the component. The validation will be reset for the parent form of this component.

<form id="testForm">
  ...
  <h:inputText id="requiredInput" required="true" />
  <o:floatingIconMessage for="requiredInput"
                         style="border: 2px solid red;"/>
  <h:commandButton action="back" value="Cancel"
                   onclick="O$.validateEnclosingForm(this);"/>
  ...
</form>

OpenFaces Validators

The OpenFaces validation framework provides several validators to complement a set of standard JSF validators. All the OpenFaces validators are supported both on the server and client side. In addition, they come with the attributes that allow you to specify validation messages for each validator.

org.openfaces.Custom

Allows you to write custom code to validate a value. This validator has two attributes to specify the code to validate a value: clientFunction and serverFunction. The clientFunction attribute should contain a JavaScript function that returns a boolean value. The serverFunction attribute should be specified as a method-binding expression that references a method that should validate a value. Please note that the serverFunction attribute is only effective for the server-side validation and the clientFunction attribute -- for the client side validation. So, to make <o:validateCustom> work both on the server and client side, you should write the validation logic twice: in the JavaScript function and in the Java method.

Tag: <o:validateCustom>
Validator ID: org.openfaces.Custom

Attributes:

Name Type EL support Default value Description
clientFunction String yes null The parameter should contain JavaScript code returning a boolean value ("true" for valid). The following variables are available:
input - the DOM element for which the validator was specified.
value - the value of the element to validate.
serverFunction javax.el.MethodExpression
(signature must match boolean action(FacesContext context, UIComponent component, Object value))
  null Reference to the method to validate the value on the server. The following variables are available:
context - FacesContext
component - validated component
value - a validated value.
The code must return a boolean value ("true" for valid).
summary String yes null The summary description of a validation error. The default value is specified in OpenFaces Message Bundle. See the section Configuring Validator Messages for additional information.
detail String yes null The detailed description of a validation error. The default value is specified in OpenFaces Message Bundle. See the section Configuring Validator Messages for additional information.

The validation checks on the client and server sides are completely independent and do not interact. If both functions, clientFunction and serverFunction, are omitted, this validator will have no sense, but this situation is not checked by the framework because it will not cause any trouble.

Note
The JavaScript code provided as the clientFunction parameter will be wrapped into a JavaScript function and invoked during client-side validation. The server-side method referenced with the serverFunction parameter will be invoked during a standard JSF validation phase on the server side .

Suppose there's a page with a text field for entering card code information. If a card with this code exists in the database, the user can see detailed information from this card. The code starts with "IC" and should not exceed the length of 10 characters. We could check these validation rules on the client side, but we need to check whether there is a card with certain code in the database.
Page:

<h:form>
 Please, enter a card code:
 <h:inputText id="cardCodeField">
      <o:validateCustom clientFunction="return (value.length>0 && value.indexOf('IC')==0);"
               detail="Card code should start with 'IC' and should be 10 characters long."
               summary="Card code validation error."/>
     <o:validateCustom serverFunction="#{Bean.testCardCode}"
               detail="Please check the card code. There is no card with code provided."
               summary="Card code validation error."/>

</h:inputText>
<h:commandButton id="viewCardButton" action="viewCard" value="view card"/>
</h:form>

Backing bean:

public class Bean(){
  ...
  public boolean testCardCode(FacesContext context, UIComponent component, Object value){
     Card card = CardCode.findCardByCode(value);
     return card!=null;
  }
  ...
}

The example above uses two validators, but it is possible to use clientFunction and serverFunction at the same time in one validator, provided they have the same error description.

org.openfaces.RegularExpression

Ensures that a value matches the pattern described as a regular expression in the pattern attribute.

Tag: <o:validateRegex>
ValidatorID: org.openfaces.RegularExpression

Attributes:

Name Type EL support Default value Description
pattern String yes null String representation of a regular expression in JavaScript form.
summary String yes null The summary description of a validation error. The default value is specified in OpenFaces Message Bundle. See the section Configuring Validator Messages for additional information.
detail String yes null The detailed description of a validation error. The default value is specified in OpenFaces Message Bundle. See the section Configuring Validator Messages for additional information.
<h:inputText id="regexValidatorField" style="width: 120px;">
  <o:validateRegex
          pattern="\+\d\d [(]\d\d\d[)] \d\d\d \d\d \d\d"
          summary="Wrong number"
          detail="Please provide phone number
                  in the following format: +xx (xxx) xxx xx xx"/>
</h:inputText>
org.openfaces.EMail

Ensures that the component has a well-formed e-mail address as a value. It is based on one of the regular expressions.

Tag: <o:validateEmail>
ValidatorID: org.openfaces.EMail

Attributes:

Name Type EL support Default value Description
summary String yes null The summary description of a validation error. The default value is specified in OpenFaces Message Bundle. See the section Configuring Validator Messages for additional information.
detail String yes null The detail description of a validation error. The default value is specified in OpenFaces Message Bundle. See the section Configuring Validator Messages for additional information.
<h:inputText id="emailValidatorField" style="width: 120px;">
  <o:validateEmail summary="Incorrect email"
                    detail="Please provide correct email address"/>
</h:inputText>
org.openfaces.URL

Ensures that the component has a valid URL as a value. Based on the regular expression.

Tag: <o:validateUrl>
ValidatorID: org.openfaces.URL

Attributes:

Name Type EL support Default value Description
summary String yes null The summary description of a validation error. The default value is specified in OpenFaces Message Bundle. See the section Configuring Validator Messages for additional information.
detail String yes null The detail description of a validation error. The default value is specified in OpenFaces Message Bundle. See the section Configuring Validator Messages for additional information.
<h:inputText id="urlValidatorField" style="width: 120px;">
  <o:validateUrl summary="Incorrect URL"
                  detail="Please provide valid URL address"/>
</h:inputText>
org.openfaces.Equal

Checks that the values of two input components are the same. In the for attribute, you should specify the component whose value must be equal to the value of the component the validator is assigned to. A common example is a double password or double e-mail address.

Tag: <o:validateEqual>
ValidatorID: org.openfaces.Equal

Attributes:

Name Type EL support Default value Description
for String no null A string representing the id of the component whose value must be equal to the value of the component this validator is assigned to.
summary String yes null The summary description of a validation error. The default value is specified in OpenFaces Message Bundle. See the section Configuring Validator Messages for additional information.
detail String yes null The detailed description of a validation error. The default value is specified in OpenFaces Message Bundle. See the section Configuring Validator Messages for additional information.

Note
The org.openfaces.Equal must be rendered after the component specified by the for attribute. 

<h:inputText id="equalValidatorField1" style="width: 120px;">
  <o:validateCustom clientFunction="return value.length > 0"
                     detail="Value should not be empty"/>
</h:inputText>
<h:inputText id="equalValidatorField2" style="width: 120px;">
  <o:validateEqual for="equalValidatorField1"/>
</h:inputText>
Configuring Validator Messages

The messages generated by the validators and converters are handled by JSF normal application message queue and can be displayed with the standard HtmlMessage and HtmlMessages components and OpenFaces FloatingIconMessage component (for more details, see the section Validation Error Message Component ). Messages have the summary and detailed description of a validation error. The messages of OpenFaces validators and converters have severity level information like those of standard JSF validators and converters. These messages are configured using a normal Java resource bundle called a message bundle with one extra rule for handling the detailed error description. The OpenFaces validation framework supports this way of specifying messages of validators and converters and provides OpenFaces Message Bundle that contains default messages for the OpenFaces validators. The client-side validation errors for the standard validators and converters which are ported to the client side are the same as for server-side validation.

In JSF standard, the parameters in the messages are filled by the framework, and there is a limited number of the parameters. For instance, if there is a parameter {0} in the message, during the rendering phase it will be replaced with the client-side id of the component for which this message will be shown. The OpenFaces validation framework supports all standard parameters for the specified messages. Also, you can use additional parameters for the OpenFaces validators. Their values should be embedded into the component with a nested MessageParam tag.

There is one more way to specify the summary and detailed error description for the OpenFaces validators. You can use the summary and detail attributes.
Example:

<h:inputText id="i1">
     <o:validateEmail detail="Please enter a valid first user's email"/>
 </h:inputText>
 <h:inputText id="i2">
     <o:validateEmail detail="Please enter a valid second user's email"/>
 </h:inputText>
MessageParam

The MessageParam component allows you to specify parameters for validation messages within any OpenFaces validator.
Tag: <o:messageParam>. Should be embedded into the validator's tag.

Attributes:

Name Type EL support Default value Description
value String yes null A string that will be used as a parameter for formatting validator or converter messages.

For example, if you have several input components with e-mail addresses, you can use a clearer message than the standard ones.
Message bundle:

org.openfaces.EMailValidatorMessage = E-mail Validator Error
org.openfaces.EMailValidatorMessage_detail = Please enter a valid \{1\} e-mail

Page:

<h:inputText id="i1">
  <o:validateEmail>
    <o:messageParam value="first user's" />
  </o:validateEmail>
</h:inputText>
<h:inputText id="i2">
  <o:validateEmail>
    <o:messageParam value="second user's" />
  </o:validateEmail>
</h:inputText>

In this case, two parameters will be accessible during formatting of the messages. Standard {0} with the client-side id of the component (it will not be used in the particular example so there is no {0} in the message body) and the next parameter {1} whose value will be first user for the first field and second user for the next one. So the message detailed description will be Please enter a valid first user's email and Please enter a valid second user's email respectively.

OpenFaces Message Bundle

Following the JavaServer Faces technology standard to access default messages via message bundles, the OpenFaces validation framework provides a message bundle (standard message.properties file ) with the following messages:

org.openfaces.CustomValidatorMessage = Validation Error
org.openfaces.CustomValidatorMessage_detail = validation error in input ''{0}''
org.openfaces.RegexValidatorMessage = Regex Validator Error
org.openfaces.RegexValidatorMessage_detail = ''{0}'': does not match regex
org.openfaces.URLValidatorMessage = URL Validator Error
org.openfaces.URLValidatorMessage_detail = ''{0}'': not a valid URL
org.openfaces.EMailValidatorMessage = E-mail Validator Error
org.openfaces.EMailValidatorMessage_detail = ''{0}'': not a valid e-mail
org.openfaces.EqualValidatorMessage = Equal Validator Error
org.openfaces.EqualValidatorMessage_detail = ''{0}'' must be equal to the ''{1}''

Parameter values:
{0} - Client-side id of the component for which the message will be displayed in case of failed validation.
{1} - Client-side id of the second component (Equal validator only).

Each message can reference the predefined parameter storing the client-side id of the component for which the message will be displayed by "{0}". (Equal validator has also a second parameter ("{1}") referencing the second component.

You can change the messages by adding a new message bundle and registering it within the application settings section in web.xml.

Annotation-based Validation

The OpenFaces validation framework provides an alternative way to configure validation - using annotations. To enable annotation-based validation you have to enclose components to be validated within <o:validateAll> tag. This tag will add server-side validators for child input components and client-side validators for supported annotations if client-side validation is enabled. See details below.

Server-side Annotation-based Validation

Server-side Annotation-based Validation supports all hibernate validator annotations and allows to define custom validator annotations by providing implementation of org.hibernate.validator.Validator interface. Please refer Hibernate Validator documentation for a list of supported annotations and on how to define your own validator.

Client-side Annotation-based Validation

This type of validation can be enabled by application-wide or form-wide client-side validation configuration. Per-component configuration is not supported yet. Please refer section Configuring Components for Client-Side Validation for details. List of supported annotations for client-side validation: @NotNull, @NotEmpty, @Email, @Length, @Pattern, @Range, @Max, @Min.

ValidateAll Component

The ValidateAll component is a container that automatically adds annotation-based validators to all child input components. Currently it is almost the same to JBossSeam's <s:validateAll> component but also provides client-side validation. It requires Hibernate annotations library to be available in classpath.

Tag: <o:validateAll>

Example:

...
<o:validateAll>	
    <h:inputText id="email" value="#{ValidateAllBean.email}"/>
    <h:message id="emailMessage" for="email" showSummary="true" showDetail="false"/><br/>

    <o:dateChooser id="registrationDate" value="#{ValidateAllBean.registrationDate}" pattern="dd/MM/yyyy"/>
    <h:message id="registrationDateMessage" for="registrationDate" showDetail="false" showSummary="true"/><br/>
<o:validateAll>	

<h:commandButton value="Submit" id="submit"/>
...

Here is an example of how the EditUserBean backing bean can be implemented:

public class EditUserBean{
  
    private Date registrationDate;
    private String email;


    @Email
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Past
    public Date getRegistrationDate() {
        return registrationDate;
    }

    public void setRegistrationDate(Date registrationDate) {
        this.registrationDate = registrationDate;
    }
}
OpenFaces