Tuesday, August 6, 2013

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.
When the user clicks the submit button without entering the user name and the phone number the following error messages are displayed.
When the user enter a invalid user name and invalid phone number the following error messages are displayed.

No comments:

Post a Comment