The expression validator is a Struts non-field validator which can be used to validate the relations among fields (or any variables in the value stack) using OGNL expression, rather than validating a single field. For example, checking if an integer field is greater than another, or checking if a date field must be after another. This validator can be used in either of the following forms:
Because this is a non-field validator so it can be only used with the plain-validator syntax as follows:
<validator type="expression"> <param name="expression">OGNL expression</param> <message>validation error message</message> </validator>
Parameter name | Description |
expression | The OGNL expression to be evaluated (to a boolean value). |
<validator type="expression"> <param name="expression">number1 lt number2</param> <message>The number #1 must be less than the number #2</message> </validator>
<validator type="expression"> <param name="expression">startDate lt endDate</param> <message>The start date must be before the end date</message> </validator>
Some OGNL comparison operators we can use are:
Usage: Put the @ExpressionValidatorannotation before the action method in the following form:
@ExpressionValidator (param1 = "param 1 value", param2 = "param 2 value", ...)
Parameter name | Required | Default value | Description |
message | Yes | Validation error message. | |
key | No | i18n key for validation error message. | |
messageParams | No | Additional parameters to customize the message. | |
shortCircuit | No | false | Whether this validator is short circuit. |
expression | Yes |
| The OGNL expression to be evaluated (to a boolean value). |
@ExpressionValidator(
expression = "number1 lt number2",
message = "The number #1 must be less than the number #2"
)
public String execute() {
return SUCCESS;
}
@ExpressionValidator(
expression = "number1 lt number2",
message = "the default message if the i18n key not found",
key = "form.validation.numbers"
)
public String execute() {
return SUCCESS;
}
Related Struts Form Validation Tutorials:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.