Reputation: 5468
I am trying to validate a list of object on Struts2.
Suppose you had a class called INVOICE
.
It has 3 properties called: product, quantity, price
And I have a list of INVOICE
called INVOICES
.
In jsp file, if you iterate over the list , it will generate these inputs.
invoices[0].product
invoices[0].quantity
invoices[0].price
invoices[1].product
invoices[1].quantity
invoices[1].price
Now after submission, I need to validate these values.
As you can see, Struts2 no longer support collection validation. http://www.opensymphony.com/webwork/api/com/opensymphony/xwork/validator/validators/CollectionFieldValidator.html
I found a way to do it with annotations. Something like
@RequiredStringValidator(message="Product name is required")
public void setProduct(String product) {
this.product = product;
}
But I am not allowed to put validation annotations on bean class due to coding standard of the project. Because I need to keep MESSAGES on properties file.
I read that I could do this validation with VisitorValidation as mentioned here. http://struts.apache.org/2.0.11.2/docs/using-visitor-field-validator.html
But I couldn't understand how to do this by seeing those examples.
Is there any way to do it with using only validation XMLs? Thank you
ANSWER:
I did it with VisitorFieldValidator, and I still had problems as I commented on correct answer.
The problem went away when I put MyModel-validation.xml
in my model package.
As the correct answer highlighted:
manage your validations for your models in one place, where they belong, next to your model classes.
Upvotes: 1
Views: 3938
Reputation: 1729
Indeed visitor field validation would be your bet bet. Struts2 documentation is not famous as being the most comprehensive, but you can get more information on the visitor field validator here, which includes a simple example.
The VisitorFieldValidator allows you to forward validation to object properties of your action using the object's own validation files. This allows you to use the ModelDriven development pattern and manage your validations for your models in one place, where they belong, next to your model classes. The VisitorFieldValidator can handle either simple Object properties, Collections of Objects, or Arrays.
In your action, you can place validation for the invoices
collection as:
<validators>
<field name="invoices">
<field-validator type="visitor">
<message></message>
</field-validator>
</field>
</validators>
Then simply proceed to create a Invoice-validation.xml
which would hold the validation logic for your Invoice
bean and place it along with the Invoice
class. For example:
<validators>
<field name="product">
<field-validator type="requiredstring">
<message>product is required.</message>
</field-validator>
</field>
</validators>
Upvotes: 2