This is where the Struts Validator "validWhen" validation rule comes into play. The validWhen rule reads: the form field is valid when the "test" variable's value is true. Or specifically looking at the confirmation password from the previous example:
<field property="confirmPassword" depends="validwhen">
<arg0 key="errors.confirmpassword.match"/>
<var> <var-name>test<var-name>
<var-value>(*this* == password)</var-value>
</var></field>
The validWhen rule works by defining a test variable with the test condition in its value. The value is a boolean expression that can contain the following (extracted from the Struts manual):
Single or double quoted string literals
Integer literals, which can be in decimal, octal, or hexadecimal form
null, which matches a literal null or an empty string
Other form fields, referenced by field name
Indexed form fields, referenced by an explicit integer, such as lastName[2]
Indexed form fields, referenced by an implicit integer, such as lastName[]; the implicit integer index will be the same index of the field being tested (for example this can be used to compare string values character by character)
Properties of indexed form fields (either with an explicit or implicit integer index), for example child[].lastName
The literal *this*, which represents the field currently being tested
Another couple notes about validWhen expressions:
They must be enclosed in parenthesis
You can only compare two values when performing an "and" or "or"
If the values can be converted to integer equivalents then they are converted and compared as such
As an example, if we wanted to allow our user to not set a password, then we would want to accept either "null" as a password or require that both the password and confirmation password match. This can be accomplished as follows:
<arg0 key="errors.confirmpassword.match"/>
<var> <var-name>test<var-name>
<var-value>((password == null ) or *this* == password)</var-value>
</var></field>
In this example, if the form's password field is null, the condition is true, or if the confirmation password (this) is equal to the password, the condition is true. Following through this logic, if password is null and confirmPassword is "ABC," the first condition is true and therefore the second condition is ignored. On the other hand, if password is "ABC" and confirmPassword is "DEF," the first condition fails (password is not null). Therefore, the second condition determines the final result; namely, is the confirmation password equal to the password, which it is not.
Writing validWhen expressions becomes easier and easier as you write them, but one of the challenges in using the validWhen is that validation errors do not appear in a JavaScript popup dialog, but rather appears in your
Note: All the above stuff is extracted from the http://www.informit.com/guides/content.aspx?g=java&seqNum=286.
Cheers,
No comments:
Post a Comment