wood burning stoves*
The moose likes Struts and the fly likes How Do You Use Struts Validator For Non Required Field? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "How Do You Use Struts Validator For Non Required Field?" Watch "How Do You Use Struts Validator For Non Required Field?" New topic
Author

How Do You Use Struts Validator For Non Required Field?

Anthony Watson
Ranch Hand

Joined: Sep 25, 2003
Posts: 327
I want to validate a form field to make sure it contains a valid email address only if the user entered text into the field before submitting the form. How can I do this and still use the server side validator logic? I was thinking I could create the paramters for the FieldChecks method that looks like this:



Is this the way I should go? If so, can somebody give me some hints on creating the ValidatorAction and Field objects? Thanks.

[ edited to break long line -ds ]
[ July 28, 2004: Message edited by: Dirk Schreckmann ]

Anthony W.<br />MCP, SCJP 1.4, SCJD, SCWCD 1.3, SCWCD 1.4, SCBCD
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
In your validation.xml file (note you may have named it something else), when you're describing the field property of the form, if you don't specify "required" as one of the "depends" value, then that field will only be based on any other "depends" values you specify, so long as the field is not empty when submitted. If it's empty, it's not validated.

On a recent project, I didn't like the default email validator provided by the Struts framework, so I wrote my own.

Here's what the logic looks like.The call to isEmail simply checks the email address against a pattern (using the java.util.regex engine).

The ValidatorAction and Field objects are generated by the Struts framework.

You'll need to register your custom validator by editing the validator-rules.xml file (which you may have named differently). In my case, I added the following global form-validation.

Does that answer your question(s)?


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Anthony Watson
Ranch Hand

Joined: Sep 25, 2003
Posts: 327
Thanks Dirk, that does answer my question. I didn't know that the validator would not try to run any validation rules other than 'required' on a field that has no data in it. Also, thanks for your example, I found the code interesting.
 
Don't get me started about those stupid light bulbs.
 
subject: How Do You Use Struts Validator For Non Required Field?