Link to home
Start Free TrialLog in
Avatar of jaggernat
jaggernat

asked on

alert messages for richtext field and fileupload control

Hi all ,
I have this question. I dont know if this has a solution though!!

I have a "rich text field" and "file upload" control to upload my coverletter and resume respectively.

Now when user enters some data in these fields,its fine ..but when she does not enter any data and submits the form, i want to display an alert message like "Please enter cover letter /resume to proceed"

This is possible with a text field in a form with the following code:

if(document.forms[0].fieldname.value == "") {
            alert(" Please enter a value in the field to continue");
           return false;
            }
else return true;

I want to have the same effect with my rich text field and fileupload control.

But the following code does not work:

if(document.forms[0].RICHTEXTFIELD.value == "") {
            alert(" Please enter a coverletter to continue");
            return false;
            }
else return true;

and neither does the following :

if(document.forms[0].FILEUPLOADCONTROL.value == "") {
            alert(" Please enter a resume to continue");
            return false;
            }
else return true;



Any solutions will be greatly appreciated.
thank you.,
J
ASKER CERTIFIED SOLUTION
Avatar of HemanthaKumar
HemanthaKumar

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jaggernat
jaggernat

ASKER

U right.. Notes does not allow to name file upload control.


As u said, I placed this code in JS header :

if(document.getElementById("FILEUPLOAD").value== "") {
            alert(" Please enter a resume to continue");
            return false;
            }
else return true;


but it popped up the following error:

"Invalid Return"



thanks,
J



hey i got it....we need to put that in "onsubmit" property  

What about the Richtext field ?


do we need to have an id for rich text field too?

thanks,
J
No not for Richtext field.. it has a name property , check the view source to make sure the richtext field is visible and has a name same as that you use in the js validation code
ok thanks ,, that was perfect.  U r name sounds indian...which part of india are you from . I am from bengal , right now doing masters in chicago,US.


thanks for the responces, i appreciate it.

J

Native of bengal tigers eh ?

Your guess is right, I am from TamilNadu. Good luck on your studies. So, Did fall start already in Chicago ?

its still warm.    but sometimes you can see rain, snow and sunlight all on the same say..:) ..As they say chicago sucks...

I wanted to ask you this .. This is my final semester and i am lookking around for jobs in US. What you think would be the best resource.

Are u in US?



thanks,
J


Yes Chicago has a weird weather pattern

If you are in PT, best chance is thru campus. Or start applying thru dice.com and monster.com.. even better a local desi consultancy can help you apply for sponsorships..

Yes I am in US..

Let us take personal chat thru mail.. hemanth at mail333 dot com
Dynamic Forms and Validation
The current stable release of Struts, v1.0.2, provides powerful development metaphors for capturing, processing, and validating the form data submitted by an end user. In medium-to-large projects, implementing an individual ActionForm class for each screen in the application can turn into a significant amount of work. The developers will find that they are writing a large number of ActionForm classes to capture the data, but are basically providing the same types of validation rules against the data.

The next release of the Strut framework, v1.1b (b standing for beta), offers two new features that promise significant reduction in the amount of work associated with building the form classes. These two new features are:

Dynamic Forms

The Validator Framework

Let's take a look at these new features and see how they can be used to build our previous example, the Post a Story page. Note that since this is a beta version of Struts, the features and their implementations described here might differ slightly when version 1.1 of the framework is released.

Dynamic Forms
As we discussed earlier in the chapter, to use Struts form processing capabilities, developers need to explicitly extend the Struts ActionForm class. They need to implement getter or setter methods for each of the form fields they wanted to capture in the class and override the reset() and validate() method inherited from the ActionForm class.

Struts v1.1b now gives the development team the ability to declaratively define an ActionForm class without writing a single line of code. To do this, we need to first define a <form-bean> class in the struts-config.xml. The following code shows the <form-bean> entry that is used to define the ActionForm (postStoryForm) class in the Post a Story page:

    <struts-config>
      <form-beans>
      <!-- Old postStoryDefinition. Please note that it uses user defined type.
            <form-bean name="postStoryForm"
                       type="com.wrox.javaedge.struts.poststory.PostStoryForm"/>
      -->
        <form-bean name="postStoryForm"
                   type="org.apache.struts.action.DynaActionForm">
          <form-property name="storyIntro" type="java.lang.String"
                         initial="Please enter a story intro!"/>
          <form-property name="storyBody" type="java.lang.String"
                         initial="Please enter a story body!"/>
          <form-property name="storyTitle" type="java.lang.String"
                         initial="Please enter a story title!"/>
        </form-bean>

        <!-- Rest of the ActionForm definitions-->
        </form-beans>
      <!-- Rest of the struts-config.xml file -->
    </struts-config>

Just like the standard non-dynamic Struts ActionForm class, we need to define the dynamic ActionForm class as a <form-bean> entry in the struts-config.xml. However, while defining a dynamic ActionForm, we do not provide our own ActionForm class in the type attribute of the <form-bean> tag. Instead, we use the org.apache.struts.Action.DynaActionForm in the type attribute:

    <form-bean name="postStoryForm"
               type="org.apache.struts.action.DynaActionForm">

Using the DynaActionForm class tells Struts that we will be using a dynamic ActionForm. Once we have defined the <form-bean>, we need to define the individual properties in it. This is equivalent to writing a get()/set() method in a non-dynamic ActionForm class:

    <form-property name="storyIntro" type="java.lang.String"
                   initial="Please enter a story intro!"/>
    <form-property name="storyBody" type="java.lang.String"
                   initial="Please enter a story body!"/>
    <form-property name="storyTitle" type="java.lang.String"
                   initial="Please enter a story title!"/>

Just like the non-dynamic example shown earlier in the chapter, our dynamic ActionForm (postStoryForm) definition has three properties: storyIntro, storyBody, and storyTitle. Each of these properties has a corresponding <form-property> tag.

A <form-property> tag has three attributes:

Attribute Name
 Attribute Description
 
name
 The name of the property and the value that will be referenced by the Struts HTML tag libraries, while accessing and setting the form data. This is a mandatory attribute.
 
type
 Fully-qualified Java class name of the attribute being set. This is a mandatory attribute.
 
initial
 The initial value that the attribute will be populated with when the reset() method for the ActionForm class is invoked. Since, this is a dynamic form, the developer does not have to override the reset() method on the form.
 

Defining the <form-bean> and its corresponding <form-property> tags is sufficient to tell Struts to use a dynamic ActionForm class. The postStoryContent.jsp page, which pulls the data from the postStoryForm form bean, does not have to be modified. It does not care whether we are using a non-dynamic or dynamic ActionForm.

Pulling the data from a dynamic form bean in the Struts Action class is done a little differently than in a non-dynamic form bean. The following code shows the rewritten PostStoryForm class (that is, the Action class), pulling the data from the dynamic postStoryForm form bean defined above:

    package com.wrox.javaedge.struts.poststory;

    import java.util.Vector;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.DynaActionForm;

    import com.wrox.javaedge.common.ApplicationException;
    import com.wrox.javaedge.member.MemberVO;
    import com.wrox.javaedge.story.StoryManagerBD;
    import com.wrox.javaedge.story.StoryVO;
    import com.wrox.javaedge.story.dao.StoryDAO;

    public class PostStory extends Action {
      public ActionForward perform(ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response){
        if (this.isCancelled(request)) {
          return (mapping.findForward("poststory.success"));
        }

        DynaActionForm postStoryForm = (DynaActionForm) form;

        HttpSession session = request.getSession();

        MemberVO memberVO = (MemberVO) session.getAttribute("memberVO");

        try{
          StoryVO storyVO = new StoryVO();
          storyVO.setStoryIntro((String)postStoryForm.get("storyIntro"));
          storyVO.setStoryTitle((String)postStoryForm.get("storyTitle"));
          storyVO.setStoryBody((String)postStoryForm.get("storyBody"));
          storyVO.setStoryAuthor(memberVO);
          storyVO.setSubmissionDate(new
                                   java.sql.Date(System.currentTimeMillis()));
          storyVO.setComments(new Vector());

          StoryManagerBD storyManager = new StoryManagerBD();
          storyManager.addStory(storyVO);
        } catch (Exception e) {
          System.err.println("An application exception has been raised in
                              PostStory.perform(): " + e.toString());
          return (mapping.findForward("system.failure"));
        }

        return (mapping.findForward("poststory.success"));
      }
    }

The difference between the above PostStory class and the PostStoryForm class shown earlier is subtle. First, the above PostStory class no longer casts the ActionForm being passed into the perform() method in the PostStoryForm class shown earlier in the chapter. Instead, it casts the incoming ActionForm parameter to be of type DynaActionForm:

    DynaActionForm postStoryForm = (DynaActionForm) form;

Then, while retrieving the data from the form, it does not call an individual getXXX() method for each property in the ActionForm. Instead, it invokes the get() method in the class by passing in the name of the property it wants to retrieve:

    storyVO.setStoryIntro((String)postStoryForm.get("storyIntro"));
    storyVO.setStoryTitle((String)postStoryForm.get("storyTitle"));
    storyVO.setStoryBody((String)postStoryForm.get("storyBody"));

The code then casts the individual properties retrieved to the Java data types that were defined in the <form-bean> tag in the struts-config.xml file.

The dynamic form bean is a powerful feature of Struts v1.1b. It allows you to easily implement and change the form beans without having to write a single line of code. This new feature keeps very much in line with the philosophy of Struts which is to let the framework do as much of the work as possible, while allowing the developer to focus on building the business code rather than the infrastructure code.

However, the real power of dynamic form beans comes into play when they are combined with another new Struts v1.1.b feature, the Validator framework.

The Validator Framework
After building several Struts-based applications, you will often find that you are performing the same types of validation over and over again. Some common validations include the following checks:

If the user has entered all required fields

If the data is within a minimum or maximum size

If the data entered is of the right type

Struts release v1.1b now provides a framework that allows you to reuse a set of common validation routines without having to write the code. This framework, called the Validator framework, allows you to write your own validation routines that can be plugged in and used across all of your own form bean classes. We are not going to discuss this framework in depth. For the purposes of this chapter, we will look at how to use it to mimic the validate() method of the PostStoryForm class shown earlier. Specifically, we are going to use a dynamic form bean to collect the form data and apply the following validation rules:

Check if the story title, story body, and story introduction fields, in the Post a Story page, are filled in by the end user

Check that each field entered by the user does not exceed a certain character length

The third validation, checking for vulgarity, will not be implemented here. Writing your own validation rules requires much more explanation. For the details on extending the validation framework with your own validation rules, please refer to the Struts documentation (http://www.jakarta.apache.org/struts).

Let's begin our discussion by looking at how the Validator framework is set up and configured.

Validator Framework Setup
The Validator framework requires a modification in the struts-config.xml file and the addition of two new configuration files: validator-rules.xml and validation.xml. Struts v1.1b allows new functionality to be added to the framework via a plug-in. The Validator framework is one such plug-in. We are not going to discuss the Struts v1.1b framework in any detail. For further information on the plug-in architecture, please refer to the Struts v1.1b documentation (http://jakarta.apache.org/struts/userGuide).

To make Struts aware of the Validator framework, we need to add the following entry (that is, <plug-in>) at the end of the JavaEdge struts-config.xml file:

    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
      <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
                                                /WEB-INF/validation.xml"/>
    </plug-in>

This defines the fully-qualified Java class that represents the plug-in point between Struts and the third-party software. The <set-property> tag is used to set a plug-in specific property. In the above example, the pathnames property contains a comma-separated list telling the Validator framework where to find the validator-rules.xml file and the validation.xml file.

The validator-rules.xml file contains individual rule entries for the pre-defined validation rules that come as part of the Validator framework. A partial listing of the validation rules defined in the validator-rules.xml is shown below:

Rule Name
 Rule Description
 
required
 Checks if the field has been filled in by the end user.
 
minlength
 Ensures that the value entered is of a minimum length.
 
maxlength
 Ensures that the value entered is of a maximum length.
 
range
 Validates that the field entered by the user falls into a certain range.
 
mask
 Validates that the field entered is of a particular format.
 
byte
 Validates that the field entered is of type byte.
 
short
 Validates that the field entered is of type short.
 
integer
 Validates that the field entered is of type integer.
 
long
 Validates that the field entered is of type long.
 
float
 Validates that the field entered is of type float.
 
double
 Validates that the field entered is of type double.
 
date
 Validates that the field entered is of type date.
 
email
 Validates that the field entered is a properly formatted e-mail address.
 

The validation.xml file contains the mappings to each form bean in that application that is going to use the Validator framework. It maps each field of the form bean to the validation rule that is going to be invoked against it. We will be going through some of the validation.xml details in the following section.

Implementing the Required Field Validation
In the Post a Story page, the story title, story introduction, and story body are all required fields. To use the Validator framework to enforce these rules, we must create a file called validation.xml. The following code shows the validation.xml file that is used to enforce the validation of the required fields:


    <form-validation>
      <formset>
        <form name="postStoryForm">
          <field property="storyTitle" depends="required">
            <msg name="required" key="error.poststory.field.null"/>
            <arg0 key="javaedge.poststory.form.titlelabel"/>  </field>
          <field property="storyIntro" depends="required">
            <msg name="required" key="error.poststory.field.null"/>
            <arg0 key="javaedge.poststory.form.introlabel"/>
          </field>
          <field property="storyBody" depends="required">
            <msg name="required" key="error.poststory.field.null"/>
            <arg0 key="javaedge.poststory.form.bodylabel"/>
          </field>
        </form>
      </formset>
    </form-validation>

The <form-validation> tag is the root element for the validation.xml file. It represents a collection of forms for the application. A <formset> tag can contain one or more <form> tags. A <form> tag represents a particular form bean in the application:

    <form name="postStoryForm">

The name attribute in the <form> tag is the name of the form bean defined in the struts-config.xml file. Each <form> tag has one or more <field> tags associated with it.

    <field property="storyTitle" depends="required">
       <msg name="required" key="error.poststory.field.null"/>
       <arg0 key="javaedge.poststory.form.titlelabel"/>
    </field>

The <field> tag represents a single element of the <form> that is going to be validated by the Validator framework. It has two attributes in it. These attributes are:

property

The name of the field that is going to be validated. This must match the name of a field defined in the <form-bean> in the struts-config.xml. This is a mandatory attribute.

depends

This lists, from left to right, all of the validation rules that are going to be invoked on the field. These rules will be fired in the order in which they are listed. In our example above, we are only applying the required rule against the field. This is a mandatory attribute.

A <field> tag can contain one or more <msg> tags. The <msg> tag is used by the Validator framework to determine which message should be displayed to the end user, when a rule is violated:

    <msg name="required" key="error.poststory.field.null"/>

A <msg> tag has three attributes:

name

The name of the rule with which the message is associated. In our above example, the value of name points to the required rule.

key

The key for the message in the Struts resource bundle (that is, ApplicationResources.properties) file. In our above example, the value of error.poststory.field.null would be pulled from the ApplicationResources.properties file as:

The following field: {0} is a required field. Please provide a value for {0}.

The key attribute is a required attribute in the <msg> tag.

resource

Tells the Validator framework that it should use the resource bundle to look up an error message, based on the value of the key attribute. If the value of resource is set to true, the resource bundle is used. If it is set to false, the default Struts resource bundle will not be used and the value in the key attribute will be taken as a literal string. The default value of the resource attribute is true.

A <field> tag can also contain argument tags called <arg0>, <arg1>, <arg2>, <arg3>, and <arg4>. These tags are used to pass arguments into the <msg> tags. The <argX> allows a developer to pass in the values to a message defined in the Struts resource bundle. The postStoryForm validation has one argument being passed into each of the messages in the field.

For example, the storyTitle uses the following <arg0> tag. It indicate that whenever a validation error occurs in the storyValidation field of the postStoryForm, the following key will be used to look up a value from the ApplicationResources.properties file and perform a string substitution on the message:

    <arg0 key="javaedge.poststory.form.titlelabel"/>

So, if the users did not enter a value into the storyTitle field, they would get the following error message:

    The following field: Story Title is a required field. Please provide a value for
    Story Title.

The <argX> tags have three attributes:

name:

Defines the name of the validation rule with which this argument is associated. For example, if we wanted only the first argument of the message to be available when the required rule is invoked for the storyTitle field, we would write the <arg0> tag as follows:

<arg0 name="required" key="javaedge.poststory.form.titlelabel"/>

If the name is not provided, this argument will be available to every validation rule that fires off a validation exception for that particular field.

key:

The key for the message in the Struts resource bundle (that is, ApplicationResources.properties) file.

resource:

Tells the Validator framework that it should use the resource bundle to look up an argument based on the value in the key attribute. If the value of resource is set to true, the resource bundle is used. If it is set to false, the default Struts resource bundle will not be used and the value of the key attribute will be taken as a literal string value. The default value of the resource attribute is true.

Once we have defined all the form and field mappings in the validation.xml file, we need to make one last change to validate our dynamic form bean against the rules we have defined. Any dynamic form bean using the Validator framework must have its <form-bean> entry modified in the struts-config.xml file. In this entry, the type attribute for the form bean must be set to use the org.apache.struts.validator.DynaValidatorForm class:

      <form-bean name="postStoryForm"
                 type="org.apache.struts.validator.DynaValidatorForm">

Now, let's look at setting up a slightly more complicated rule, the maxlength validation rule.

The maxlength Validation Rule
The next rule that we are going to implement, for our rewritten Post a Story page, puts some maximum size limit on the data entered by the user in each field. It is the maxlength validation rule.

The following code shows the revised validation.xml file, containing the new definitions of the rules:

    <form-validation>
      <formset>
        <form name="postStoryForm">

          <field property="storyTitle" depends="required,maxlength">
            <msg name="required" key="error.poststory.field.null"/>
            <msg name="maxlength" key="error.poststory.field.length"/>
            <arg0 key="javaedge.poststory.form.titlelabel"/>
            <arg1 name="maxlength" key="${var:maxlength}" resource="false"/>
            <var>
              <var-name>maxlength</var-name>
              <var-value>100</var-value>
            </var>
          </field>

          <field property="storyIntro" depends="required,maxlength">
            <msg name="required" key="error.poststory.field.null"/>
            <msg name="maxlength" key="error.poststory.field.length"/>
            <arg0 key="javaedge.poststory.form.introlabel"/>
            <arg1 name="maxlength" key="${var:maxlength}" resource="false"/>
            <var>
              <var-name>maxlength</var-name>
              <var-value>2048</var-value>
            </var>
          </field>

          <field property="storyBody" depends="required,maxlength">
            <msg name="required" key="error.poststory.field.null"/>
            <msg name="maxlength" key="error.poststory.field.length"/>
            <arg0 key="javaedge.poststory.form.bodylabel"/>
            <arg1 name="maxlength" key="${var:maxlength}" resource="false"/>
            <var>
              <var-name>maxlength</var-name>
              <var-value>100000</var-value>
            </var>
          </field>

        </form>
      </formset>
    </form-validation>

To set up each field with the maxlength validation rule, we need to add the rule to the value of the depends attribute in each <field> tag. For the storyTitle field, this would look like:

    <field property="storyIntro" depends="required,maxlength">

The rules are always invoked from left to right. In the above validation.xml file, the required validation rule will be invoked before the maxlength rule.

For the two rules associated with each field, we need to add <msg> tags that will reflect the different messages for each rule. In the storyTitle, we have two <msg> tags with the name attribute of each being the same as one of the names defined in the depends attribute:

    <msg name="required" key="error.poststory.field.null"/>
    <msg name="maxlength" key="error.poststory.field.length"/>

In addition, each message has two arguments passed to it. Thus, there are <arg0> and <arg1> tags defined in each <field> tag. For the storyTitle field, it is as shown below:

    <arg0 key="javaedge.poststory.form.titlelabel"/>
    <arg1 name="maxlength" key="${var:maxlength}" resource="false"/>

The first argument, <arg0>, is going to be shared across all the messages being thrown by the validation field. To do this, we do not define the name attribute in the <arg0> tag. However, the second argument, <arg1> is going to be available only to the maxlength validation rule. We indicate this by setting the name attribute in the <arg1> tag to maxlength.

We need to define the constraints for the validation rule to take effect. For instance, for the maxlength validation rule, we need to specify the acceptable maximum length of the field being validated. This value can be set by using the <var> tag. The maxlength validation rule takes a single parameter, maxlength, as an input value:


    <var>
      <var-name>maxlength</var-name>
      <var-value>100000</var-var>
    </var>

The <var> tag contains two elements, <var-name> and <var-value>. The <var-name> element holds the name of the input parameter being passed into the validation rule. The <var-value> element holds the value that is to be set for that variable.

The table below lists all of the validation rules that accept the input parameters:

Rule Name
 Parameters
 Parameter Description
 
minlength
 Min
 Integer value representing the minimum size of the field.
 
maxlength
 Max
 Integer value representing the maximum size of the field.
 
Range
 Min, max
 Integer value representing the minimum and maximum size for the field.
 
Mask
 Mask
 Regular expression indicating the mask to be applied to the field.
 
Date
 Datepattern
 Date pattern that is to be applied against the field to determine whether or not the user has entered a proper date.
 

In the <arg1> tag you would have noticed the unusual syntax of the key attribute. The key attribute is set to the value ${var:maxlength}. This value will pull the value defined for the <var> tag whose <var-name> is equal to maxlength. However, the value of this variable will be pulled only if the resource attribute in the <arg1> tag is set to false.

Some Final Thoughts
Discussing how to use the Struts development framework is out of the scope of this book. The next release of Struts promises to offer many new features and enhancements, which will make the form processing and validation extremely automated. The section Dynamic Forms and Validation of this chapter has discussed these new features very briefly, particularly the Validator framework.

There are some other important topics on the Validator framework such as:

Retrofitting the Validator framework into earlier versions of Struts

Extending the Validator framework to include custom validation rules

The discussion on these topics is out of the scope of this book. For more information on these topics, you can visit the Struts web site (http://jakarta.apache.org/struts).