Solved

Struts dynamic form validation

Posted on 2004-09-08
7
2,835 Views
Last Modified: 2008-02-01
Hi Experts,

I am new to struts. And I hope someone can guide me on the following:
I have a form which all the form fields are dynamic generated from database.
How can I perform validation for those dynamic field?

Thank you

0
Comment
Question by:totoron
  • 3
  • 3
7 Comments
 

Expert Comment

by:mylenereiners
ID: 12004483
Do you have to validate?
I mean, if the data are in the database they should be ok (or at least I hope).

But if you need it: you can turn on validation (on a page-by-page basis) in struts-config.xml.
And have a look at the Validator and DynaForms to perform the validation

Success,

Mylene
0
 

Author Comment

by:totoron
ID: 12005824
The data are not in the database yet. I have to verify the data entered are correct before I store to database.
However each field in the form are very dynamic according to the country selected.
Eg: User chooses United States,
The form for this User may have the following fields for their address:
-Apt
- City
-Postcode

Whereas user chooses Singapore, may have the following fields for their address:
- Block
- Street
- Unit number
- Postcode

I need to verify user enters the correct data.
Since all these fields are dynamic(retrieve from database), how do I validate those fields.
Can someone give an example?
Thanks
0
 
LVL 11

Accepted Solution

by:
sompol_kiatkamolchai earned 500 total points
ID: 12006470
if you use strust framework you can create validate() method in form bean which jsp container will call it automatically when the form is created as set to value.

you should start with creating form that contains all posible fields from every country like this

public class AddressFormBean {
  private String apt;
  private String city;
  private String postcode;
  private String block;
  private String street;
  private String unitNumber;
  private String postcode;

  public String getApt() {
    return this.apt;
  }
 
  public void setApt(String apt) {
    this.apt = apt;
  }
  ...
  ... // other fields accessor method or getter and setter
  ...
 
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
    {
        ActionErrors errors = new ActionErrors();

        if(getApp() == null || getApp().equals(""))
            errors.add("apt", new ActionError("error.AptErrorMessage"));
        if(getCity() == null || getCity().equals(""))
            errors.add("city", new ActionError("error.CityErrorMessage"));
        try
        {
            int  temp = Integer.parseInt(getPostcode());
        }
        catch (NumberFormatException e)
        {
            errors.add("postcode", new ActionError("error.PostcodeErrorMessage"));
        }
        ...
        .... //more validate other fields...
        ....
        return errors;
    }
}

when you submit form to action then struts frame work will look in struts-config.xml for type of
form bean to create. after create and call all setters method. it will call validate if there is errors
return from this method it will redirect to jsp file you specify.

for more detail
http://publib.boulder.ibm.com/infocenter/iadthelp/index.jsp?topic=/com.ibm.etools.struts.doc/html/tstruse0024.htm
http://struts.apache.org/
0
Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 

Author Comment

by:totoron
ID: 12012507
Thanks. I didn't list out all the possible fields.
I plan to use hashmap to keep all the fields that I have extracted from Database.
My code is as below.
However, I can't get my validation error message pop up. Is there anything that I missed out.
Please advise.


public class WarrantyRegForm extends ValidatorForm{
       
   public Map fields = new HashMap();
    public ArrayList vali = new ArrayList();
   
     public Object getField(String key)
    {    
        return fields.get(key);
     }
 
    public void setField(String key, Object field)
    {
            fields.put(key,field);
     }
 
       public ActionErrors validate( ActionMapping mapping, HttpServletRequest request ) {
        ActionErrors errors = new ActionErrors();
        HttpSession session=request.getSession();
        vali =(ArrayList)session.getAttribute(Constants.LOCALIZED_ADD);
     
        for(int i=0; i<vali.size(); i++){
            String key= (String)vali.get(i);
               if ( getField(key) == null || ((String) getField(key)).length() < 1 ) {
                System.out.println(getField(key)+"Print out null here?");
                errors.add("key",new ActionError("errors.add"));
            }  
           
        }
        System.out.println(errors);
        return errors;
           
}
     
}
0
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
ID: 12016384
http://struts.apache.org/userGuide/building_view.html#form_validation

If I have more time, I will help you more. Maybe tomorrow.
0
 

Author Comment

by:totoron
ID: 12023981
Ok. Thanks.
Is there any method which I don't have to explicitly list out all the properties to do the validation?
0
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
ID: 12024021
You must have property file that contain error message.
As you can see

errors.add("key",new ActionError("errors.add"));

the errors.add is one entry point in property file like this

errors.add=Tell the user what the error is.
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
constructor overloading 2 83
Coldfusion 10 - JSP File Not Found - 404 Error 5 93
servlet concurrency 13 102
Is it possible to "sandbox" html content within a JSP? 4 101
Each year, investment in cloud platforms grows more than 20% (https://www.immun.io/hubfs/Immunio_2016/Content/Marketing/Cloud-Security-Report-2016.pdf?submissionGuid=a8d80a00-6fee-4b85-81db-a4e28f681762) as an increasing number of companies begin to…
This article outlines why you need to choose a backup solution that protects your entire environment – including your VMware ESXi and Microsoft Hyper-V virtualization hosts – not just your virtual machines.
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question