In this example we will see how to do
date validation and email validation in struts using validator framework. Our
userForm is of type org.apache.struts.validator.DynaValidatorForm. It contains
two fields dob and emailId. We use date rule to validate date of birth and email rule to validate email id. The struts-config.xml file contains the
following code to define the userForm.
1.<form-beans>
2.<form-bean name="userForm"type="org.apache.struts.validator.DynaValidatorForm">
3.<form-property name="dob" type="java.lang.String" />
4.<form-property name="emailId" type="java.lang.String" />
5.</form-bean>
6.</form-beans>
Note that the dob
is of type String. If any other primitive type is specified, Struts will try to
convert the incoming parameter into that primitive type. If the input is
invalid, then the validations will not run properly. Whenever the form field is
subjected to any validation use java.lang.String as its type.
The validation.xml
file contains the following codes.
01.<form name="userForm">
02.<field property="dob" depends="required,date">
03.<arg key="userForm.dob"/>
04.<var>
05.<var-name>datePattern</var-name>
06.<var-value>MM-dd-yy</var-value>
07.</var>
08.</field>
09.<field property="emailId" depends="required,email">
10.<arg key="userForm.emailId"/>
11.</field>
12.</form>
The name attribute of the form tag in
validation.xml contains the name specified in the name attribute of the
form-bean tag in struts-config.xml, in this way we associate the validations
with the form attributes. Here we need to first validate whether the date is
entered or not, for that we use therequired rule.
We use the date rule to validate date. The date rule checks whether the entered date is
valid or not. The datePattern variable is used to specify the pattern used by the date. The
datePattern is implemented using java.text.SimpleDateFormat. In this example we
use the following date pattern "MM-dd-yy". In this case the dates can
be anything like this 03-21-86, 3-21-86, 03-21-1986. If you want the date to
have a strict date format then you need to use datePatternStrict. If the
datePatternStrict value is "MM-dd-yy", then it will accept only dates
like 03-21-86.
Inorder to perform the email
validation we use the email rule. We use the required rule to make sure the email id is entered and then we use the email rule to vaidate the email id.
The following
messages should be configured in the ApplicationResource.properties file. If an
invalid data is entered by the user, then the following values will be used to
display the appropriate error messages.
1.userForm.dob = Date Of Birth
2.userForm.emailId = Email Id
On runing this
sample date validation example the following page is displayed. The user needs
to enter a valid date and email id to register successfully.
No comments:
Post a Comment