Useful validation methods like validateRequired , validateEmail , validateCreditCard , validateInteger , validateDate , ValidateMinLength and lotmore methods are already packaged with Struts Validator Framework . But application may require some specific validation method which may not be available with Struts validator. But it has a flexibility to create and add new validation rules which can be reused in any form. Writing custom validation method in a action form may not be reused . So you need to write in every form. Now let us create a custom validation method and add to the validation-rules.xml. For example , an Employee is assigned a target date to complete the work .The employer should not assign a date which is already past or sunday. DateValidate method is available in validation-rules.xml to check wheather the given date is valid (dd/MM/yyyy) or not. Now we have to write code for checking the given date is already passed or sunday .
Major Steps to create custom validation
1. Writing code for validation method
2. Adding Validation rule for the above method in the validation-rules.xml file
3. Adding new validation definitions to validation.xml file
4. Adding necessary error messages in the ApplicationResources.properties / MessageResources.properties.
Now let us go through the above steps in detail
Ist Step is writing code for Validation Method in our example it is sundayValidate to check the given date is already passed or sunday . The vaildation method should have the arguments / signatures as given below public static boolean validateSunday(Object bean,ValidatorAction val_action,Field field,ActionErrors errors,HttpServletRequest request) . The complete code is as follows. The validateSunday method is written in a class . In our example it is written in the class ValidationUtil under the util package.
In the above method , Object is Form Bean object which contains the field values to be validated. Field object retrieves the <field> definition (field name) from the validation.xml for the field which is currently being validated. getValueAsString() method is used to retrieve the value for the field name (in our example targetDate) returned by the field.getProperty() from the Form bean . The logic checks the targetDate date is sunday or it is a past date . If it is sunday or old date , then the error message is added to ActionError object.
Now the 2nd step is adding Validation rule for the above method in the validation-rules.xml file
The validation method is given a name (in our example sunday) by using name attribute as given above . We have to also mention the class name of the method using classname attribute . Method name is mentioned by method attribute . The above validation rule can be referenced by field tag's depends attribute using name (in our example sunday) . Note : Validation rule must be placed in <global> element in validation-rules.xml file.
Now 3rd step is adding new validation definitions to validation.xml file whic is as follows .
In the above definition field tag mentions the property name to be validated . depends attribute mentions the method reference to be called for validation. required calls the requiredMethod , date calls the dateValidate . sunday calls the sundayValidate which is a custom validation method written by us and defined in the validation-rules.xml file. required and date are already defined by default in the validation-rules.xml file with errors.required and errors.date message
Final and 4th step is adding error messages to ApplicationResources.properties
The jsp code (part) is given below.
targetDate.jsp
The struts-config.xml (part) code is as follows
empForm code (part) is given below
Major Steps to create custom validation
1. Writing code for validation method
2. Adding Validation rule for the above method in the validation-rules.xml file
3. Adding new validation definitions to validation.xml file
4. Adding necessary error messages in the ApplicationResources.properties / MessageResources.properties.
Now let us go through the above steps in detail
Ist Step is writing code for Validation Method in our example it is sundayValidate to check the given date is already passed or sunday . The vaildation method should have the arguments / signatures as given below public static boolean validateSunday(Object bean,ValidatorAction val_action,Field field,ActionErrors errors,HttpServletRequest request) . The complete code is as follows. The validateSunday method is written in a class . In our example it is written in the class ValidationUtil under the util package.
package util;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.validator.Resources;
public class ValidationUtil
{
public static boolean validateSunday(Object bean,ValidatorAction val_action,Field field,ActionErrors errors,HttpServletRequest request) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
try {
Calendar cal = Calendar.getInstance();
Calendar today = Calendar.getInstance();
today.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH), 12,0,0);
int dd=Integer.parseInt(value.substring(0,2));
int mm =Integer.parseInt(value.substring(3,5));
int yyyy = Integer.parseInt(value.substring(6,10));
cal.set(yyyy ,mm-1, dd ,12,0,0);
int DOW = cal.get(Calendar.DAY_OF_WEEK); // 1=Monday
if (cal.before(today) || (DOW-1)==0) {
errors.add(field.getKey(), Resources.getActionError(request,val_action,field));
return false;
}
} catch (Exception e) {
errors.add(field.getKey(), Resources.getActionError(request,val_action,field));
return false;
}
return true;
}
}
In the above method , Object is Form Bean object which contains the field values to be validated. Field object retrieves the <field> definition (field name) from the validation.xml for the field which is currently being validated. getValueAsString() method is used to retrieve the value for the field name (in our example targetDate) returned by the field.getProperty() from the Form bean . The logic checks the targetDate date is sunday or it is a past date . If it is sunday or old date , then the error message is added to ActionError object.
Now the 2nd step is adding Validation rule for the above method in the validation-rules.xml file
<form-validation>
<global>
.....
......
<validator name="sunday" classname="util.ValidationUtil" method="validateSunday"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
depends=""
msg="errors.sunday">
</validator>
.....
</global>
</form-validation>
The validation method is given a name (in our example sunday) by using name attribute as given above . We have to also mention the class name of the method using classname attribute . Method name is mentioned by method attribute . The above validation rule can be referenced by field tag's depends attribute using name (in our example sunday) . Note : Validation rule must be placed in <global> element in validation-rules.xml file.
Now 3rd step is adding new validation definitions to validation.xml file whic is as follows .
<form-validation>
<formset>
.....
<form name="targetFrm">
<field property="empCode" depends="required">
<arg0 key="targetFrm.empCode" />
</field>
<field property="targetDate" depends="required, date, sunday">
<arg0 key="targetFrm.targetDate" />
<arg1 key="targetFrm.targetDate" />
<arg2 key="targetFrm.targetDate" />
<var>
<var-name>datePatternStrict</var-name>
<var-value>dd/MM/yyyy</var-value>
</var>
</field>
</form>
....
</formset>
</form-validation>
In the above definition field tag mentions the property name to be validated . depends attribute mentions the method reference to be called for validation. required calls the requiredMethod , date calls the dateValidate . sunday calls the sundayValidate which is a custom validation method written by us and defined in the validation-rules.xml file. required and date are already defined by default in the validation-rules.xml file with errors.required and errors.date message
Final and 4th step is adding error messages to ApplicationResources.properties
targetFrm.empCode=Employee Code
targetFrm.targetDate=Target Date
# general error msgs
errors.required={0} is required.
errors.sunday={0} is either old date or Sunday
The jsp code (part) is given below.
targetDate.jsp
<HTML>
......
<TITLE>Employee Targetdate assign</TITLE>
</HEAD>
<body> <html:errors />
<html:javascript formName="targetFrm" />
<html:form action="/targetDate">
<bean:message key="targetFrm.empCode" />
<html:text property="empCode"></html:text> <br />
<bean:message key="targetFrm.targetDate" />
<html:text property="targetDate"></html:text> <br />
<html:submit value="Submit"></html:submit>
</html:form> </body>
....
</HTML>
The struts-config.xml (part) code is as follows
<form-beans>
</form-bean>
<form-bean name="targetFrm" type="strutsvalidatorweb.forms.empForm">
</form-bean>
</form-beans>
<action-mappings>
<action name="targetFrm" path="/targetDate" scope="request" type="strutsvalidatorweb.actions.empEnty" validate="true" input="/targetDate.jsp" parameter="method">
<forward name="target" path="./target.jsp">
</forward>
</action>
</action-mappings>
empForm code (part) is given below
public class empForm extends ValidatorForm {
private String empCode = null;
private String targetDate=null;
public String getEmpCode() {return empCode;}
public String getEmpName() {return empName;}
public String getTargetDate() {return targetDate;}
public void setTargetDate(String string) {targetDate = string;}
}
For more detail about Struts Validator Framework with example , please visit Struts validator framework example
Output :
Note : In the above jsp , input date should be given as dd/MM/yyyy (total 10 digits , year should be in 4 digits) because we have given date pattern as datePatternStrict with the value dd/MM/yyyy. Other date format strictly not accepted. To accept other format you have to give datePattern , but you need to change code to split the date in the the validateSunday method .
Read more...