Struts 1 > Struts Mask Validation Rule Example

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.

    <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" />

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"/>
    <field property="phoneNumber" depends="required,mask">
        <msg name="mask" key="userForm.phoneNumber.mask" />
        <arg key="userForm.phoneNumber"/>

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 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
Contact Us  |  Copyright © 2012