Organize validation messages in Struts2 validation(XML)

456 Views Asked by At

I am trying to do validations in struts 2 for my current project. I have to group my validation messages. For Eg: If there are 3 fields that are empty and there are 3 other fields whose format is not right, I need to get a msg like "The following fields are required: field1, field2, field3 The format of the following fields are invalid: field4, field5, field6"

I tried providing a param to fieldError. Eg:
< s : fielderror >
< s : param value="%{requiredstring}"/>
< / s : fielderror>

According to me this is like specifying "show all errors whose validator type is requiredstring". Please correct me if I am wrong. But this will display the message "The following fields are required" each time for every field that is empty. I want it displayed only once.

Is there a way to do this cleanly in stuts2 using validation through xml? I donot want to do all the validations in a validate method.

Thanks

1

There are 1 best solutions below

1
On

You are wrong; I have no idea why you thought that'd work, the docs don't imply that's possible.

Field errors are just that--errors for a specific field. If you need to group errors by arbitrary criteria, like the validation type, you'll need to implement that yourself.

There are a number of ways to do this, including writing a custom validation interceptor, providing validators that group errors in a different way, or simply gathering the appropriate messages in an action or validation method.

You could gather errors based on the message content, but IMO that would be brittle. If this is a cross-application issue, you're better off doing it a different way.

All that said, by presenting error messages in an order not necessarily reflective of the form, you're pushing more cognitive overhead onto the user: I don't want to see groups of messages telling me which fields share the same error, I want to see what's wrong with each field, in the same order the fields are presented on the form, preferably near the form field itself.