Pages

Wednesday, 11 September 2013

How To Apply Multiple XML Validations On Same Field In Struts 2

i there, this is very important concept in real time, applying multiple validation rules on same field.  For example we have Email filed and we would like to apply 2 validations to this field like email, requiredstring. [ hey these 2 are rules right,  just go back and check the previous concept if not clear :-) ]
So we want users to enter email id which contains only string value.
Actually by default if one rule, suppose requiredstring failed no need to check email rule right, but by default struts 2 will verify email rule also.  So to avoid this, we need to write short-circuit=”true”.  What am saying if we apply 5 rules to one filed then if 1 rule is failed there is no need to check others right… :-) that what am saying hope it make sense.
Example:
Note: If first rule [ requiredstring ] failed, then struts 2 will not verify email rule as we given short-cricuit=”true”.  Same concept even if you apply 1000 rules hah  :-) and that’s it nothing is more than this.
You can check practically in the next example….!!!!!!

Struts2 Validation Rules and Their Syntax



For every rule there is a class, all classes here are implements Validator interface
  • required
  • requiredstring
  • stringlength
  • int
  • double
  • date
  • email
  • url
  • fieldexpression
  • regex
  • few other rules are there but light..!!
For each rule given, there is an implementation class exist for it as told above.
Example:
For ‘required’ rule the class name is RequiredFieldValidator, for ‘int’ the class name is IntRangeFieldValidator
If we want to create our own validator class then our class should also implements validator interface.  Validator interface is given in com.opensymphony.xwork2.validators.*.
required
This rule verify whether user entered value is null or not, hear we cannot pass any parameters
Example:
1
2
3
4
5
<field name="uname">
   <field-validator type="required">
        <message> User name is mandatory </message>
   </field-validator>
</field>
requiredstring
This will validates whether the input entered is a valid string or not we can pass a parameter called trim to this rule.
Trim will removes extra space from left and right sides of given word
Example:
1
2
3
4
5
6
<field name="uname">
   <field-validator type="requiredstring">
        <param name="trim">true</param>
        <message> you must enter string value </message>
   </field-validator>
</field>
stringlength
This rule validates whether the given input is with in the given range of characters or not.  This rule is the combination of both min, max length rules.
To this rule we can pass either both parameters min length and max length or any one of the paramenters
Example:
1
2
3
4
5
6
7
<field name="uname">
   <field-validator type="requiredstring">
        <param name="minLength">8</param>
        <param name="maxLength">12</param>
        <message> user name should be with in ${minLength} and ${maxLength} characters </message>
   </field-validator>
</field>
int
This rule verifies whether the given input value is with in the given range of integer or not, To this rule we need to pass min, max parameters
Example:
1
2
3
4
5
6
7
<field name="uname">
   <field-validator type="int">
        <param name="min">25</param>
        <param name="max">35</param>
        <message>Age should be in between ${min} and ${max} </message>
   </field-validator>
</field>
Note: Actually ‘double‘ also same as int, but we need to pass the parameters minInclusive,maxInclusive
date
This will validate whether the given input date is with in the range of the dates or not, we need to pass min, max parameters to this rule.
When we enter the date values then the format to be followed is dd-mm-yyyy
Example:
1
2
3
4
5
6
7
<field name="dob">
   <field-validator type="date">
        <param name="min">01/01/2011</param>
        <param name="max">01/01/2020</param>
        <message>year should be in between ${min} and ${max} </message>
   </field-validator>
</field>
And email, url are simple just like required, we no need to pass any parameters hope you are good.
fieldexpression
In struts 1.x, with validator frame work we can do only per field validations, i mean we can validate field by field.  But hear in struts 2,x we can do the between field validations also with this fieldexpression rule.
Actually if we want to do between fields in struts 1.x, we must do manually but hear we can do this via xwork validator framework which supports both per-field and between filed validations also.
To work with this rule we must pass one parameter named ‘expression‘
Between field means, we can compare the current entered value with any one of above field.
Example:
1
2
3
4
5
6
7
8
9
10
11
<field name="myDateOfBirth">
   <field-validator type="fieldexpression">
        <param name="expression">

          <! [ CDATA[#myDateOfBirth < #myFatherBirth]] >            

        </param>

        <message>Your Birth date must be less then your father dob</message>
   </field-validator>
</field>
Note: here #myFatherBirth is other field name

XML Validations In Struts2 With Examples



Let us see the XML validations in struts2, we used to call this type of validations as declarative, what ever.  In struts2 if we want to apply the declarative validations then we need to use a set of per-defined validation rules, that are given by the framework.  All pre-defined rules are configured in an xml file called validators.xml.  In struts2 along with jar files added in the application, this validators.xml file also will be loaded automatically.  If we want to create any custom validators (user defined) then we need to copy validators.xml into classes folder of our web application and then we need to configure our validator into validators.xml, if we don’t want any custom validations then no need to copy this validators.xml into classes folder.
If we want to apply xml validations for client inputs then we can do it in the following 2 ways.
  • By creating a validation.xml file for our Action class
  • By creating a validation.xml file for an Action alias
Actually if we have multiple business methods exist in an action class then we configure the same action for multiple times.
Example:
Let our action class name MyAction,  and we have setters, getters with 2 business methods execute1() and execute2(), as if we are going to get 2 types of validations on the same variables, like for Admin, User.
  • If my url is, loginuser.do then my validations file name will be MyAction-loginuser-validator.xml
  • If my url is, loginadmin.do then my xml file must be MyAction-loginadmin-validator.xml
In struts.xml
We need to configure our Action class 2 times but we will specify the execute() method name like…
1
2
3
4
5
6
7
8
9
<action name="/loginuser.do" class="MyAction" method="execute1" >
-- - --- - -
------- - --- --
</action>

<action name="/loginadmin.do" class="MyAction" method="execute2" >
-- - --- - -
------- - --- --
</action>
Note: This is the case if we want to apply separate validations for same input values, if we want single set of validations, then xml file name will be MyAction-validator.xml
If we want to apply single time xml validations for our action class then our xml file name should be
(Action class name)-validation.xml
If we want to apply different set of validations on same action class like Admin,User then xml file name should be
(Action class name)-Alias-validation.xml
Remember:  We need to store our validation xml files in the classes folder of the web application
Syntax of our validation.xml in struts2
1
2
3
4
5
6
7
8
--- dtd ---
<validators>
<field name="firstName">
   <field-validator type="rule name">
         <message> some message </message>
   </field>
</field>
</validators>