This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How Do You Use Struts Validator For Non Required Field?

 
Anthony Watson
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)?
 
Anthony Watson
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic