Meyyappan has posted 101 posts at DZone. View Full User Profile

Struts Mask Validation Rule Example

06.15.2012
| 18244 views |
  • submit to reddit

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.

<form-beans>
    <form-bean name="userForm" type="org.apache.struts.validator.DynaValidatorForm">
        <form-property name="userName" type="java.lang.String" />
        <form-property name="phoneNumber" type="java.lang.String" />
    </form-bean>
</form-beans>

The validation.xml file contains the following codes.

<form name="userForm">
    <field property="userName" depends="required,mask">
        <msg name="mask" key="userForm.username.mask" />
        <arg key="userForm.username"/>
        <var>
            <var-name>mask</var-name>
            <var-value>^[a-zA-Z]*$</var-value>
        </var>
    </field>
    <field property="phoneNumber" depends="required,mask">
        <msg name="mask" key="userForm.phoneNumber.mask" />
        <arg key="userForm.phoneNumber"/>
        <var>
            <var-name>mask</var-name>
            <var-value>^[0-9]*$</var-value>
        </var>
    </field>
</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.

userForm.username.mask = {0} should contain only alphabets.
userForm.phoneNumber.mask = {0} should contain only numbers.
userForm.username = User Name
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.

You can download the source code of the mask validation example by clicking on the Download link below.

Source: Download

Source + Lib: Download

Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: