Struts 1.3 Validator Framework Example- step by step guide.

The following steps guides the process of installing and configuring the Struts 1.2 or 1.3  Validator component. The Struts Validator depends on various libraries to work properly. It requires the following libraries

->commons-collections.jar

->commons-beanutils.jar

->commons-logging.jar

->commons-digester.jar

The above JAR files needs to be either in Application Server (Tomcat/WebSphere) common/lib directory or in the Web application’s WEB-INF/lib directory.

For Using Validator Framework,two XML files are required.

1. validation-rules.xml

2. validator.xml.

validation-rules.xml specifies the validation rules available. As the Validator comes with several default rules, we have to copy it into application’s WEB-INF directory. The following lines are some of the default validation rules available in the validation-rules.xml

// Sample Validation-rules.xml

Default error messages associated with each validator defined in validator-rules.xml file should be added to ApplicationResources.properties file or you can associate new ones by modifying the pluggable validators msg attributes in this file.

ApplicationResources.properties commonly located in your applications JavaSource/props folder.

Sample ApplicationResources.properties

errors.invalid={0} is invalid.

errors.minlength={0} can not be less than {1} characters.

errors.required={0} is required.

errors.date={0} is not a date.

 

Validator plugin

Now the following lines need to be added in the structs-config.xml for connecting the Validator to the application.

Sample Validation.xml

Example :

Now we are going to see how to use Validator in our application by creating a small Struts project. In our example, we will create a Employee form which will accept Employee Name, Age, Email, Mobile Number

Step 1) Create a Employee Form (empForm.Jsp). The JSP is as follows

Step 2) Create an Employee ActionForm. The code in the ActionForm is as follows

EmpForm.java

Step 3) Define validations for the ActionForm in validation.xml file as given below.

Step 4) Writing Error Messages in ApplicationResources.properties

label.empCode=Employee Code
label.empName=Employee Name
label.age=Age
label.email=Email
label.mobile=MobileNo

errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short 

Step 5) The Entries in struts-config.xml is as follows which includes Validator Plug-in

Step 6) Run the Application and the output is as follows.

You may also like

Leave a Reply

Be the First to Comment!