Search

Struts Custom Validation Example

In this example we will see how to do custom validation in struts. To perform custom validation we extend the UserForm from org.apache.struts.validator.ValidatorForm. The UserForm contains two fields one for the phone number and the other for the mobile number. Lets take the senario where either phone number or mobile number is mandatory. If the validation takes into account only one field at a time then Struts Validation Framework does an excellent job. What if we need to consider more than one form field to validate data. In this case we go for custom validation.
The UserForm class contains the following code.
01.public class UserForm extends org.apache.struts.validator.ValidatorForm {
02. 
03.private String phoneNumber;
04.private String mobileNumber;
05. 
06.public String getPhoneNumber() {
07.return phoneNumber;
08.}
09. 
10.public void setPhoneNumber(String phoneNumber) {
11.this.phoneNumber = phoneNumber;
12.}
13. 
14.public String getMobileNumber() {
15.return mobileNumber;
16.}
17. 
18.public void setMobileNumber(String mobileNumber) {
19.this.mobileNumber = mobileNumber;
20.}
21. 
22.public UserForm() {
23.super();
24.}
25. 
26.public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
27.ActionErrors errors = super.validate(mapping, request);
28.if ((getPhoneNumber() == null || getPhoneNumber().length() < 1) &&
29.(getMobileNumber() == null || getMobileNumber().length() < 1)) {
30.errors.add("phoneNumber"newActionMessage("error.phoneNumber.required"));
31.}
32.return errors;
33.}
34.}
We will override the validate method in the UserForm to perform custom validation. First we call the super class validate method inorder to save any errors returned by the ValidatorForm. Then we check whether the mobile number or phone number is present. If both are not present then we create a new ActionError and add the errors to it. After performing all the validations we will save the errors if any and return the ActionError object. If any errors are present the user will be forwarded to the input page ( in our case it's the user.jsp page).
The following message should be configured in the ApplicationResource.properties file. If either phone number or mobile number is not entered by the user then the following error message will be displayed.
1.error.phoneNumber.required = Either Phone number of Mobile number is required.
On runing this sample custom validation example the following page is displayed. The user needs to enter either phone number or mobile number to enter successfully.
 






Date and Email Validation Tutorial

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.
 






Struts Mask Validation Rule Example

In this example you will see how to use the mask rule to restrict the user input. Here the userForm has two fields, one for the user name and the other for the phone number. We will restrict the user to enter only alphabets in the user name field and only numbers in the phone number field. The struts-config.xml file has the following entry for userForm.
1.<form-beans>
2.<form-bean name="userForm"type="org.apache.struts.validator.DynaValidatorForm">
3.<form-property name="userName" type="java.lang.String" />
4.<form-property name="phoneNumber" type="java.lang.String" />
5.</form-bean>
6.</form-beans>
The validation.xml file contains the following codes.
01.<form name="userForm">
02.<field property="userName" depends="required,mask">
03.<msg name="mask" key="userForm.username.mask" />
04.<arg key="userForm.username"/>
05.<var>
06.<var-name>mask</var-name>
07.<var-value>^[a-zA-Z]*$</var-value>
08.</var>
09.</field>
10.<field property="phoneNumber" depends="required,mask">
11.<msg name="mask" key="userForm.phoneNumber.mask" />
12.<arg key="userForm.phoneNumber"/>
13.<var>
14.<var-name>mask</var-name>
15.<var-value>^[0-9]*$</var-value>
16.</var>
17.</field>
18.</form>
The required rule is used to ensure that the value is entered by the user and the mask rule is used to restrict the user from entering invalid data.
The following messages should be configured in the ApplicationResource.properties file. If invalid data is entered by the user, then these values will be used to display the appropriate error message.
1.userForm.username.mask = {0} should contain only alphabets.
2.userForm.phoneNumber.mask = {0} should contain only numbers.
3.userForm.username = User Name
4.userForm.phoneNumber = Phone Number
The "userForm.username.mask" value is used to display the error message when an invalid user name is entered.
On running this sample mask validation rule example the following page is displayed. The user needs to enter a valid user name and phone number to register successfully.