File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Struts and the fly likes Best practice for Validation? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "Best practice for Validation?" Watch "Best practice for Validation?" New topic

Best practice for Validation?

Nate Leech
Ranch Hand

Joined: Feb 07, 2005
Posts: 43
I have a form in a jsp that I validate against using Struts Validation Framework. So I make my own custom Validation Method that uses methods from my database class to access the database and validate against it, to check for things like if a record already exists or something along those lines.

Is it good practice to have custom validation methods make calls to a database? Or should this only happen in the Action Class, where I would add an ActionMessage and then findforward to the requesting page?

Any help is greatly appreciated!

Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
Your suspicions are correct. Even though you can do validation that accesses the database in custom validation methods, generally speaking it's better to do those types of things in an Action form. One of the main reasons for doing this is that in the Action form you have more flexibility around what to do if an error occurs.


Consultant, Sima Solutions
Marc Peabody
pie sneak

Joined: Feb 05, 2003
Posts: 4727

I disagree with Merrill here.

My belief is that the ActionForm's validate method should only contain simple syntax validation to answer questions like, "Did the user enter a valid date in this textfield?"

What you are explaining about hitting the DB is business validation, which belongs in the Action's realm. The Action should be responsible for handling any business logic validation errors. The Action should hit a delegate and if any problems are found down the chain, an exception can be thrown that the Action can catch and create an ActionMessage for.

A good workman is known by his tools.
Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
My previous post did not correctly state my position. My intention was to state that the best place to do this type of validation is in the Action CLASS not the Action Form.

So, I agree with Marc on this.

I agree. Here's the link:
subject: Best practice for Validation?
jQuery in Action, 3rd edition