Struts Tutorial Home

Struts Home

JSP Resources

Community

Site

Using validation framework in our application not only provide the basic routines for the validations but also gives the user flexibility to create their own specific validator rules for the application. This is the powerful extensible feature as this saves a lot more development and validation time during the application development. Below is given the complete set of changes which should be performed while creating the custom validator rules for the application.


Steps to create the Validator rules :-



  1. Create a class and add the static method for the validation.

  2. Add the entry in the validator-rules.xml file.

  3. Associate the rule with the form field.

  4. Add the property in the MessageResources.properties for the error message.


Example


Note:- The example is merged with the "Extending the Validation Rules with the inherited SubForm classes". You can see the marks field which can only take values from 1 to 100. The below is the validation class for the example.


 


package com.visualbuilder.validator;


import java.io.Serializable;


import javax.servlet.http.HttpServletRequest;


import org.apache.commons.validator.Field;
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;


/**
* This class is a custom validator which when apply to the framework checks The
* field should contain only alphabets
*
*/

public class CustomValidator implements Serializable {


public static boolean checkForRange(Object bean, ValidatorAction va, Field field, ActionMessages errors, Validator validator,
HttpServletRequest request) {
    boolean result = false;
    String value = evaluateBean(bean, field);
    try {
            if (Integer.parseInt(value) > 0 && Integer.parseInt(value) < 100) {
                            result = true;
                        }
                } catch (Exception e) {
                }
        if (!result) {
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                }
        return result;
    }


private static String evaluateBean(Object bean, Field field) {
        String value = null;
    if (bean instanceof String) {
        value = (String) bean;
        } else {
        value = ValidatorUtils.getValueAsString(bean, field.getProperty());
        }
    return value;
    }


}
                    

Copyright © 2013 VisualBuilder. All rights reserved