Struts custom validation rule tutorial

The struts validation framework comes packaged with several useful validations that will suit for most situations, the struts validation comes with validation rule like required, minlenght, and maxlength etc. however, your web application may require a specific validation that is not provided by the struts validation framework. So in this case, the struts validator framework provides a simple interface for creating your own custom validations that can easily be plugged into the validation framework. Below is the list of the steps you need to take to create your own custom validation rule.

1. Create a new validation rule method.

2. Add a new validation rule to the validation-rules.xml file.

3. Applying new validation rule to form bean field inside validation.xml file.

4. Add messages to the ApplicationResources.properties file.

In our example we will develop the validation rule for mobile no field, which will validate the valid Indian mobile no format.

Creating a validation rule method

The first step in creating a custom validation is to create a validation method that can be called by the struts validator framework.

You can write the method in any class, the method should return a Boolean literal. In our we are going to write a class which have the validateMobile () method, the code of example validation rule class in given below.

 
 
package com.java.struts.validator;
 
import javax.servlet.http.HttpServletRequest;
 
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.Resources;
 
public class RegistrationValidator {
 
    public static boolean validateMobile(Object bean, ValidatorAction action,
        Field field, ActionMessages errors, Validator validator,
            HttpServletRequest request) {
 
        String value = null;
        if (isString(bean)) {
            value = (String) bean;
        } else {
            value = ValidatorUtils.getValueAsString(bean, field.getProperty());
        }
 
        if (!GenericValidator.isBlankOrNull(value)) {
            if (value.startsWith("0")) {
                if (value.length() != 11) {
                    errors.add(field.getKey(), 
                        Resources.getActionMessage(validator, request, action, field));
                    return false;
                } else {
                    try {
                        Long.valueOf(value);
                    } catch (Exception e) {
                        errors.add(field.getKey(), 
                            Resources.getActionMessage(validator, request, action, field));
                        return false;
                    }
                }
            } else if (value.startsWith("+91")) {
                if (value.length() != 13) {
                    errors.add(field.getKey(), 
                        Resources.getActionMessage(validator, request, action, field));
                    return false;
                } else {
                    try {
                        Long.valueOf(value.substring(1));
                    } catch (Exception e) {
                        errors.add(field.getKey(), 
                            Resources.getActionMessage(validator, request, action, field));
                        return false;
                    }
                }
            } else {
                errors.add(field.getKey(), 
                    Resources.getActionMessage(validator, request, action, field));
                return false;
            }
        }
        return true;
    }
 
    protected static boolean isString(Object o) {
        return (o == null) ? true : String.class.isInstance(o);
    }
}
 
 
 

The validateMobile() method begins by retrieving the value for the field being validated. The value is retrieved by determining the field’s name with a call to field. getProperty ) and then looking up that field in the Form Bean with a call to ValidatorUtil.getValueAsString(). The getValueAsString() method matches the name of the field with the name of one of the Form Bean fields and then gets that field’s value. The rest of the validateMobile() method performs the actual validation logic. If the validation fails for any reason, an error message will be stored in the errors ActionMessages object.

Adding a new validation rule inside validation-rules.xml

After the custom validation rule code has been created, a new validation rule needs to be added to the validation-rules.xml file.

The code of adding into validation-rules.xml is shown below.

 
<validator name="required"
            classname="com.java.struts.validator.RegistrationValidator"
               method="validateMobile"
         methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionMessages,
                       org.apache.commons.validator.Validator,
                       javax.servlet.http.HttpServletRequest"
              depends=""
                  msg="errors.mobile"/>
 

The validation rule applies a name to the validation with the name attribute, in our example we have specify name as mobile. You also need to specify the class in which the validation method is housed with the classname attribute, and specifies the validation method’s arguments with the methodParams attribute. The msg attribute specifies a key that will be used to look up an error message in the application’s resource bundle file ApplicationResources.properties, if the validation fails. The name applied with the name attribute is the logical name for the rule and it will be used to apply the rule to definitions in the validation.xml file.

Applying new validation rule to form bean field

Once you have defined your custom validation rule in the validation-rules.xml file, you can make use of it by referencing its logical name in the validation.xml file:

In order to use the mobile validation you will update our the validation.xml for mobile no field of registration form bean as shown below.

 
 
<field property="mobile" depends="required,mobile">
    <arg0 key="registration.mobile" />
</field>
 
 
 

In the preceding validation definition, each of the comma-delimited values of the field tag’s depends attribute corresponds to the logical name of a validation rule defined in the validation-rules.xml file.

Adding messages to the ApplicationResources.properties file

The final step in creating a custom validation is to add messages to the ApplicationResources.properties file:

 
 
registration.mobile=Mobile no
 
errors.mobile='{0}' field is not a valid mobile no.
 
 
 

Remember that the errors.mobile message key was specified by the msg attribute of the validator tag for the custom validation rule in the validation-rules.xml file. The key’s corresponding message will be used if the validation fails. The registration.mobile message key was specified by the arg tag of the validation definition in the validation.xml file. Its corresponding message will be used as the parametric replacement for the errors.mobile message’s {0} parameter. So, if the mobile custom validation fails, the following error message will be generated by substituting the registration.mobile message for {0} in the errors.mobile message as:

 
 
'Mobile no' field is not a valid mobile no.