In this tutorial you will see how to perform date and email validation using the Struts Validation Framework.
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.
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.
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 the required 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.
userForm.dob = Date Of Birth
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.
When the user clicks the submit button without entering the date of birth and the email id the following error messages are displayed.
When a valid date of birth is entered and the email id is not entered the following error message is displayed to the user.
When an invalid email id is entered the following error message is displayed to the user.
You can download the source code of this example by clicking on the Download link below.