Assertions
Assertions are used to validate complex conditions among multiple form fields or input parameters. The <assert> element specifies a boolean EL expression in its mandatory test attribute.
Assertions are the last step in form validation. Assert expressions are evaluated in a variable context, which allows the following implicit objects:
- requestScope, sessionScope, moduleScope, applicationScope - request, session, module, application scope maps.
- param - HTTP parameter map.
- moduleContext - module context instance.
- input - Form input map, associating form input names with the unvalidated form input strings.
- property - Form data map, associating form data property names with the validated form data values.
During expression evaluation, all inputs referenced by the implicit objects input and property are collected. If the expression evaluates to false, the following rules apply:
- If the result depends on a reference to an invalid input, it will be ignored.
- Otherwise, the assertion has failed and the referenced inputs are marked.
The nested <message> element gives the message to be generated if the assertion fails.
Example
The following example shows a form definition with two input fields (account number and creditcard number). The assertion at the end assures that exactly one of the fields has been filled with valid data (i.e. a long value to keep it simple).
<form name="bankData">
<field property="account">
<convert name="long">
<property name="groupingUsed" value="false"/>
<message>
<arg name="field" bundle="foo.msg" key="label.account"/>
</message>
</convert>
</field>
<field property="creditcard">
<convert name="long">
<property name="groupingUsed" value="false"/>
<message>
<arg name="field" bundle="foo.msg" key="label.creditcard"/>
</message>
</convert>
</field>
<assert test="empty property.account != empty property.creditcard">
<message bundle="foo.msg" key="error.oneOf">
<arg bundle="foo.msg" key="label.account"/>
<arg bundle="foo.msg" key="label.creditcard"/>
</message>
</assert>
</form>
The required entries in your msg.properties file might look like these:
error.oneOf=Either field '{0}' or field '{1}' has to be filled (not both)
label.account=Account Number
label.creditcard=Creditcard Number


