STRUTS

Page 148

135

Working with Dates

Working with Dates Suppose that you want to track the birth dates of your users with the user registration form. To do this, you could use the date rule. The date rule checks to see if the field is a valid date. The datePattern variable specifies the pattern used to parse the date; if it is not specified, the short form of the date is used. The datePattern format is specified in the JavaDocs for java.text.SimpleDateFormat because the underlying implementation uses java.text.SimpleDateFormat. Instead of datePattern, you could specify a datePatternStrict variable. The datePatternStrict variable will ensure that 5-29-70 does not work; when the pattern MM-dd-yyyy is used, only 05-29-1970 works (notice the 0 before the 5). The following code ensures that users enter dates using the pattern MM-dd-yyyy: <field property="birthDate" depends="date"> <arg0 key="userRegistration.birthDate" /> <var> <var-name>datePattern</var-name> <var-value>MM-dd-yyyy</var-value> </var> </field>

Thus, 05-29-1970 would be a valid date but 99-29-1970 would be an invalid date. This code assumes that you have added a string property to your userRegistration form bean. To make 5-29-1970 an invalid date, you would use the strict form as follows: <field property="birthDate" depends="date"> <arg0 key="userRegistration.birthDate" /> <var> <var-name>datePatternStrict</var-name> <var-value>MM-dd-yyyy</var-value> </var> </field>

Notice with both date validations, the user could decide to enter no date at all. Hence, the way you coded the code above implies that birth date is an optional field. Essentially, this rule determines the date only if it is present; otherwise, it is happy to validate a blank field. To make the date required, you would add the required rule to the front of the depends attribute.

Jakarta Struts Live


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.