Performing Validator Plug-in Based Client Side Declarative Form Validation

Performing validator plug-in based client side declarative form validation:-

Step1:- Perform all the ten steps of previous class on Struts app’s (StrutsDemo App1-Dv)

Step2:- Take formpage as input page of action class (register.jsp)

Step3:- Add html: java Script tag in the form page having form bean logicalname

                 <html: javascript form name = “rf”/>

Note: – The above step generated one dynamic javascript function having the javascript code of form validation (validator plug-in supply) that javascript function name notation is validate form bean logical name.

        Validate <FormBean logicalname>(this)

  • if form bean logical name is “rf” then the function name would be validateRF (-)

    For example if form bean logical name is “abc” then the function name could be validateABC (-)

Call the above step generated dynamic javascript function against on submit event in <html: form> tag of form page.

                On submit = “return validateRF (this)”

Register.jsp:-

          <html: javascript formname = “rf”/>

< html:form-action = “register” method= “get” on submit = “return ValidateRF (this)”>

Username: < html: text property= “username”/> < html: errors property= “username”/><br>

Password: < html: password property= “password”/> < html: errors property= “password”/><br>

    <html: submit value = “checkDetails”/>

    </html: form>

Note: –   Since validator plug-in performs both cliect side & server side form validations even though script code (javascript) even is disabled through browser settings, the server side form validation ligic takes place automatically.                                

To disable scriptcode in Internet Explorer:-

  1.  Select Tools and the following
  2. Internet
  3. security tab
  4. logical internet
  5. custome label
  6. Scripting
  7. Actionscripting
  8. disable.

Procedure to Apply Validation Plugin based Validation Rules

Procedure to apply validator plug-in based validation rules (required rules on Struts application with respect to 1st App).

Step1: Configure validator plug-in Struts-config file

               In Struts-config.xml (After <location-mapping> tag).

                 <message-resources>

               < Plug-in classname = “org.apache.Struts.validator.ValidatorForm”>

<set-property property = “pathname” value = “/WEB-INF/ validator-rules.xml, /WEB-INF/ validation.xml”/>

   </plug-in>

(Gather it form Struts/apps/apps folder supplied example App)

Step2:- Arrange validate-rules.xml file in WEB-INF folder of Struts App by extracting it form Struts-core-1.3.8.jar file

Step3:- prepares properties file in WEB-INF / classes folder having validator rules related default error.messages.

          [WEB-INF / classes / myfile.properties / Struts validator ErrorMessages]

                 Errors.requied = {0} is required

                 Errors.minlength = {0} cannot be less than {1} characters.

Note: – we can collect the above 14 default error messages form the comment of validator-rules.xml file.

Step4:- configure above properties file in Struts-config file.

              In Struts-config.xml file (after </action-mapping>)

                    <message-resources parameter = “myfile”/>

Step5:- make your form bean class extending form the predefined validator form class.

Register Form.java

             Package app;

              Important org.apache.Struts.action.*;

              Important org.apache.Struts.validator.*;

             Public class RegisterForm extends validatorForm

                         {

                            Private string username;

                           Private string password;

                            Public RegisterForm ()

                               {

                                   S.O.pln (“RegisterForm (): o=param constructor”);

                               }

                         Public void set username………..

                                 {

                                }

Complete the above form bean class javac – d.*.java

Step6:- Develop validation.xml file in WEB-INF folder configuring validator rules on form bean properties (required rule).

Note: – gather this file from Struts/apps/apps folder related example app & modify its needed.

Validation.xml

                <!DOCTYPE     ————-    ltd>

                   <form-validation>

                     <formset>

                          <form name = “rf”>

                             <field properties = “username” depends = “required”>

                                 <arg position = “0” key = my.un“/>

                   </field>

             <field property = “password” depends = “required”>

                         <arg position + “0” key = “my.pass”/>

                </field>

              </form>

             </formset>

            </form-validation>

  • The “required” validator rule related default error msg is errors.required = {0} is repuired.

Step7:- Add user defined msg to properties file supplying argument {n} values of default error messages.

              In myfile.properties (take this ‘3’ lines)

                 # User defined msgs supplying {0} value for required rule error msg.

                       My.un = Login username

                       My.pass = login password

Step8: – Configure input page for action class to display form validation error-messages.

In Struts-config.xml:-

               <a-m>

                 <action path = “register” type = “app.RegisterAction” name = “rf” input =

                                                                                                                   /”register.jsp”>

            <forward>

          </action>

        </a-m>

Step9:– Add <html: errors> in the input page to display positions

In Register.jsp:-

                          ———

                        ———-

                     ———-

                 <html: errors1>

Step10:- Develop remaining resources of app like 1st App (Struts Demo App1)

  • While working with validator plug-in we can still four fixed keeps to apply styles on error messages.

           Errors.header = <font color = red size = 1>

          Errors.footer = ———–

          Errors.prefix = ———–

           Errors.suffix = ————–

While working with validation plug-in the form bean property name it self acts as form validation error logicalname when validations errors are generated on that form bean property in the above step based example App. to display form validation error-messages with respect to form component positions write following code in

Register.jsp

             <% % ——— tag-html %>

              <html: form action = “register” method = “get”>

   Username: < html: text property= “username”/> < html: errors property= “username”/><br>

   Password: < html: property= “username”/> < html: errors property= “password”/><br>

         < html: submit value= “CheckDetails”/>

           </ html: form>

  • Form bean properties name adding as Logical name of form validation errors Generated by validator plug-in.

App2:-

1)      Register.jsp–>replace inl—>form page, input page, result page

2)      Web.xml—> td file

3)      Validation.xmll—>td file to configure validator plug-in resated validation rules.

4)      RegisterForm.java

5)      registerAction.java

6)      myfile.properties

Validator plug-in Recognise and Activate in Struts Application

Question:- When validator plug-in will be recognized and will be activated in Struts application.

Answer:-    When ActionServlet reads Struts-configuration file entries (especially <plug-in> tag) the validator plug-in will recognize. This generally takes place either during server startup or during the deployment of web application, when servlet-container creates & initializes ActionServlet class object.

Validator plug-in will be activated to perform form validations based on validation.xml file entries, when ActionServlet calls validate (-) method of our form bean class related super class. (Validate () method of validatorForm class).

Validator-Rules.xml File in Struts – Struts Tutorial

Validator-rules.xml file contains the following details:-

  • Default error messages validator rules
  • The class name, method names where the java code of validator rules reside….
  • The .jsp file names where the java script code of validator rules reside.
  • Various other details of validator rules

Note: – programmer just needs to arrange this file in Struts application. There is no need of editing this file.

The default error messages of validator rules are:-

  • Error.required = {0} is required
  • Error.email = {0} is invalid email
  • Error.date = {0} is not a date

{n}—none

Argument values are error-messages should be supplied by the programmer to complete the error messages with respect to the form components.

Example: – {0} is required message of required validator rule:-becomes: user-name is required when it is applied on username property(textbox) becomes: address is required when it is applied on address property (textbox)

Programmer uses validation.xml :-

a)      To configure his choce validator rule on form bean properties to perform form validation.

b)      Supplies {n} argument values for default error messages of validator rules.

c)       Provides instruction to vlalidator plug-in to generate the neccary javacode, javascript code based on validator rules that are configured on form bean class properties.

  • Is order to work with validator plug-in supplied validator rules our form bean class must extend from    org.apache.Struts.validator.validatorForm class (this class is sub class of ActionForm class).          

                    – org.apache.Struts.validator.ValidatorForm
                    –  org.apache.Struts.action.ActionForm

  • The form bean class that extends from regular Action class cannot work with validator plug-in based validations.
  • If “validate ()” method of our form bean class executes programmatic form validation will take place.
  • If validate() of our form bean class related super class (validate () of predefined validateForm class) executes then the  validator plugin based declarative form validation takes place based on the configuration done in validation.xml file because this method can activate validator plug-in.

Procedure to Perform Client Side Programmatic Form Validation

Procedure to perform client side programmatic form validation with respect to StrutsDemoApp1-pv application:-

Step1:- write java script code as shown below in the form page of Struts application (register.jsp)

In register.jsp:-

  •            <%@
  •           <%@
  •           <%@
  •         <html>
  •           <head>
  •            <script language = “Javascript”>
  •                   Function myvalidate (frm)
  •                    {
  •                     //read form data
  •                      Var unval = frm.username.value;
  •                Var pwdval = frm.password.value;
  •              //write programmatic client-side form validation logic
  •            If (unval ==””)
  •                {
  •                  Alert (“username is required”);
  •                    Frm.username.focus ();
  •                   Return false:
  •                  }
  •          Else {
  •                Var fchar = unval.charAt (0);
  •                    If (! is NaN (fchar))
  •                        {
  •                          Alert (“username must begin with alphabet”);
  •                          Frm.username.focus ();
  •                         Frm.username.value=””;
  •                      Return false;
  •                   }
  •               }
  •       If (pwdval == “”)
  •          {
  •                   Alert (“password is required”);
  •                       Frm.password.focus ();
  •                           Return false;
  •           }
  •                   Else {
  •                Var fchar = pwdval.charAt (0);
  •                    If (! is NaN (fchar))
  •                        {
  •                          Alert (“password must begin with alphabet”);
  •                          Frm.password.focus ();
  •                         Frm.password.value=””;
  •                      Return false;
  •                   }
  •               }
  •       Return true;
  •          } //my validate (-,-)
  •     </script>
  •       </head>

    < html:from action = “register” method = “get” onsubmit = “return myvalidate (this)”>

Username: < html: text property= “username”/> < html: errors property= “unerr”/><br>

Password: < html: password property= “password”/> < html: errors property= “pwderr”/><br>

        <html: submit value= “checkDetails”/>

              </html>

Result is : <logic: not Empty name = “msg”>

                      <bean: wrote name = “msg”>

                        </logic: not Empty>

Step2: – Develop the remaining resources

  • Validation plugin supplies sct of readily available form validation logic as form validation rules having both java codes, java script code to perform client side & server side form validation in declaration mode.
  • A plug-in is a patch s/w\s/w application that can enhance the functionality of existing s/w or s/w applications.
  • In Struts environment validation plug-in, tiles plug-in’s are supplied to enhance the functionalities of Struts applications.
  • In Struts environment every plug-in contains one plug-in class name implementing org.apache.Struts.action.plug-in interface.
  • When validation plug-in is used for client side form validations the relevant javascript code will be activated when validate plug-in is used for server side form validation the relevant java code will be activated.

The Plug-in class name of validation plug-in is:

         Org.apache.Struts.validator.validatorplug-in

The Plug-in class name of tiles plug-in is:

                      Org.apache.Struts.tiles.Tilesplug-in

  • To use any plug-in in our Struts application its plug-in class must be configured in Struts configuration file as shown below.

In s-c.xml:-

<plug-in classname = “org.apache.Struts.validator.validatorplug-in”>

<set-property property = “pathnames” value = “/WEB-INF/ validator-rules.xml, /WEB-INF/ validation.xml”/>

  • Declarative form validation means the programmer uses already available form validation logic / rules of validator plug-in to validate the form data.
  • Validator plug-in supplied validator rules are required maxlength, minlingth, date, email, credit card and etc. since validator rules are predefined while working with validator plug-in.
  • All validator rules related details configuration are there in validator rules.xml file. This file can be collected from Struts-home \ lib \ Struts-core-1.3.8.jar file.

Display Form Validation Errors with Respect to the Position of their Form Components

Question:-  How to display form validation errors with respect to the position of their form components?

step1:- Remove <ul> tag, <li> tag effects from properties file.

In myfile.properties:-

            # to apply style on Form validation error messages

             Errors.header = <font color = blue size = 1>

            Errors.footer = </font>

Step2:- use <html: errors> tag with properties attribute as shown below in the input page of Action class.                

Reg.jsp:-

         <%@

          <%@

          <%@

           <html: form action = “register” method = “get”>

             Username: <html: text property = “username”/> <html: errors property = “unerr”/><br>

             Password: <html: password property = “password”/> <html: errors property = “pwderr”/><br>

             <html: submit value = “checkDetails”/>

             </html: form>

  • Logical names given for form validations while adding them as elements of ActionErrors class object in the validate (-,-) of method of form bean class refer step: (3) of previous class.

Difference between ActionErrors, ActionMessage and ActionError class

Question:- Can you explain about ActionErrors, ActionMessage, ActionError class?

  1. ActionErrors class object represents all form validation errors of form page in the form of multiple elements. This is a Map Data structure and each element represents one form validation error. In this each element key & values will be there where key represents logical name of form validation error and value represent ActionMessage/ActionError class object having form validation error message.
  • From struts 1.3 on wards the ActionError class is removed. So you can work with ActionMessage class as alternate.

ActionErrors class obj (it is like map data structure)

Unerr –> Keys New ActionMessage/ActionError(“my.un.req.err”);–> Values
unerr New ActionMessage/ActionError(“my.un.alpha.err”);
pwderr New ActionMessage/ActionError(“my.pass.req.err”);
pwderr New ActionMessage/ActionError(“my.pass.alpha.err”);
  • Logical name of one form validation error
  • key-represents error message in properties file
  • When multiple form validations are there a single bean property then it is recommended to give same logical name for all those form validation errors.
  • To apply styles and efforts on form validation error messages add the following keys (fixed) based message in properties file.

In myfile.properties :-

        # to apply styles on form validation error messages.

         Errors.header = <ul> <font color = red size 2>

         Errors.footer = </font></url>

         Errors.prefix = <li>

         Errors.suffix = </il>

Note: – The above keys based style will not be applied on presentation logic labels of jsp.

  • The style of “errors.header” key comes only for one time at the beginning of all the error messages. Lly “errors.footer” based style will come at the end of all the error messages.
  • “errors.prefix” styles will come at beginning of each error message. Where as “errors.suffix” styles will come at the end of each message.

Server Side Programmatic Form Validation – Struts Tutorial

Procedure to perform server side programmatic form validation with respect to our first Struts application:-

Note: – For the above requirement we need to write the java code based form validation logic by overriding the validation () in our form bean class.

Step1:- Prepare properties file having form validation error messages.

Myfile.properties :-

     # user-defined form validation error message

    My.un.req.err = Logic username is required

    My.pass.req.err = Logic password is required

    My.un.alpha.err = Logic username must being with an alphatbet

    My.pass.alpha.err = Logic password must being with an alphatbet

Note: – in the above file keys & values are user defined

Step2:- configure properties file in Struts-configuration file

In Struts-configuration.xml:-   

Step3:- override validate () method in form bean class as shown below.

In RegisterForm.java:-

 

 

 

 

Step4:- configure input jsp page for Struts action class (RegisterAction class)

The jsp page using which the form validation errors will be displayed.

Step5:- Add html errors tag in the input jsp program to decide the position of displaying from validation error messages.

 

Step5:- Develop the remaining resource of Struts application like our first application.

Form Validation in Struts Application – Struts Tutorial

Form validation in Struts Application:-

Proto type of validate () method:-

       Form1:-  Public ActionErrors validate (ActionMapping mapping, HttpServletRequest request)

       Form2:-  Public ActionErrors validate (ActionMapping mapping, ServletRequest request)

                    Form1 validate () method is recommended.

  • ActionError class object is internally map data Structure it contains elements representing form validation errors.
  • When validate () of form bean class returns ActionErrors class object without elements (size is zero) (indicates no form validation errors) then ActionServlet transfors control to the execute () method of Action class.
  • If validate () method of form bean class returns ActionError class object with elements (size is > 0) (indicates form validation errors are there) then ActionServlet transfers the control to input jsp to display form validation error messages.

Understanding Problem with Check Box of Form Page in Session Scoped Form Bean Environment

Understanding problem with check box of form page in session scoped form bean environment:-

form page struts

 

  • In the above diagram check box is not selected for second request but form bean class object is showing the selected state value for check box related form bean property which is wrong value (showing unmarried person as married person)
  • To solve the above diagram problem there are 2 solutions.

Solution1:- Change the form bean class object scope to request form Session. Here for every request is generated by form page one separated new form bean class object will be created so any request cannot utilize previous request data. 

Note: – In sol (1) we are not actually solving the problem; we are escaping from the problem by changing form bean scope to “request”.

Solution2:- By working with reset (-) even though the form bean class object scope is Session.

  • ActionServlet calls reset (-,-) methods for every request generated by form page before calling setxxx () methods. Programmer generally keeps not selected state values for check box, list box related form bean properties in this reset () method definition. 

Note: – Donnot use reset () to set initial values to form bean properties be3 programmer can do this work during the declaration of form bean prepeties.

Prototype of reset () method:-

  • Public void reset (ActionMapping mapping, httpServletRequest request)
  • Public void reset (ActionMapping mapping, ServletRequest request)
  • While overriding reset () method in our form bean class the array type form bean properties of check box, list box properties we need to assign not selected state values by initialize them with at list element size (1) with respect to Details project related details form class (form bean) the reset () must be overridden as shown below when form bean scope is Session.