在Struts中应用Validator进行两个字段的比较的方法。

04-03-19 chenjianxiong

在struts中进行采用Validator进行输入验证有很多好处,完全可以通过修改XML文件来根据客户的要求定制数据验证而不用修改代码。但是Valiator没有提供现成的进行两个字段比较的验证方法,如验证输入密码和确认密码一致,后面的日期必须大于前面的日期等等。下面是我实现的两个字段进行比较的验证方法,可以进行两个字段是字符串、日期、数字类型的数据的比较。下面是我的实现方法,望指正:

package com.sysway.quintum.validator;

import java.io.Serializable;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DecimalFormat;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericTypeValidator;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.validator.Resources;
import com.sysway.quintum.validator.WrapData;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: Sysway Co.Ltd</p>
 * @author chen jianxiong
 * @version 1.0
 * @usage:
 *<validator name="compareTwoFields"
       classname="com.sysway.quintum.validator.CompareTwoFieldsValidator"
       method="validateTwoFields"
       msg="errors.twofields"/>
      <field property="password"
       depends="required,twofields">
          <arg0 key="typeForm.password.displayname"/>
          <var>
             <var-name>secondField</var-name>
             <var-value>confirmedPassword</var-value>
          </var>
          <var>
             <var-name>dataType</var-name>
             <var-value>String</var-value>
          </var>
          <var>
             <var-name>logicOperate</var-name>
             <var-value>Great</var-value>
          </var>
          <var>
             <var-name>pattern</var-name>
             <var-value>yyyy-mm-dd</var-value>
          </var>
     </field>
     * @logicOperate:equal, greaterEqual, greaterThan, lessEqual, lessThan, notEqual
     * @dataType:String,date,Number
     * @pattern:yyyy-mm-dd

 */

public class CompareTwoFieldsValidator implements Serializable {
    public static boolean validateTwoFields(Object bean, ValidatorAction va,
            Field field, ActionErrors errors, HttpServletRequest request) {
        String firstFieldValue = ValidatorUtil.getValueAsString(bean, field.getProperty());
        String secondFieldName = field.getVarValue("secondField");
        String secondFieldValue = ValidatorUtil.getValueAsString(bean, secondFieldName);
        if (!GenericValidator.isBlankOrNull(firstFieldValue) &&
            !GenericValidator.isBlankOrNull(secondFieldValue)) {
            String logicOperate = field.getVarValue("logicOperate");
            String dataType = field.getVarValue("dataType");
            String pattern = field.getVarValue("pattern");
//            System.out.println("firstFieldValue:" + firstFieldValue + "," +
//                               "secondFieldName:" + secondFieldName + "," +
//                               "secondFieldValue:" + secondFieldValue + "," +
//                               "logicOperate:" + logicOperate + "," +
//                               "dataType:" + dataType + "," +
//                               "pattern:" + pattern);
            Object oValue1 = null, oValue2 = null;
            try {
                if (dataType.equals("Number")) {
                    DecimalFormat df = new DecimalFormat();
                    oValue1 =  df.parse(firstFieldValue);
                    oValue2 = df.parse(secondFieldValue);
                }
                else if (dataType.equals("Date")) {
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    oValue1 = sdf.parse(firstFieldValue);
                    oValue2 = sdf.parse(secondFieldValue);
                }
                else {
                    oValue1 = (String ) firstFieldValue;
                    oValue2 = (String ) secondFieldValue;
                }
            }
            catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
            try {
                if (logicOperate.equals("equal")) {
                    if (WrapData.compareTo(oValue1, oValue2) == WrapData.EQUAL)
                     return true;
                    else {
                        errors.add(field.getKey(),
                               Resources.getActionError(request, va, field));
                        return false;
                    }
                }
                else if (logicOperate.equals("greaterThan")) {
                    if (WrapData.compareTo(oValue1, oValue2) == WrapData.GREATERTHAN)
                        return true;
                    else {
                        errors.add(field.getKey(),
                               Resources.getActionError(request, va, field));
                        return false;
                    }
                }
                else {
                    errors.add(field.getKey(),
                               Resources.getActionError(request, va, field));
                    return false;
                }
/*                else if (logicOperate.equals("greaterEqual")) {
                }
                else if (logicOperate.equals("lessEqual")) {
                }
                else if (logicOperate.equals("lessThan")) {
                }
                else if (logicOperate.equals("notEqual")) {
                }*/
            } catch (Exception e) {
                errors.add(field.getKey(),
                           Resources.getActionError(request, va, field));
                return false;
            }
        }
        else {
            errors.add(field.getKey(),
                           Resources.getActionError(request, va, field));
            return false;
        }
    }
}

<p>

chenjianxiong
2004-03-19 14:51

validation.xml使用示例:

<form name="changePasswordForm">
        <field property="oldPassword" depends="required">
           <arg0 key="oldPassword"/>
         </field>

         <field property="password" depends="required">
           <arg0 key="password"/>
         </field>

         <field property="confirmedPassword" depends="twoFields">
           <arg0 key="confirmedPassword"/>
           <arg1 key="${var:logicOperate}"/>
           <arg2 key="${var:secondField}"/>
           <var>
             <var-name>secondField</var-name>
             <var-value>password</var-value>
           </var>
           <var>
             <var-name>dataType</var-name>
             <var-value>String</var-value>
           </var>
           <var>
             <var-name>logicOperate</var-name>
             <var-value>equal</var-value>
           </var>
         </field>
      </form>

<p>

chenjianxiong
2004-03-19 14:53

validation-rules.xml中定义规则:

<validator name="twoFields"
            classname="com.sysway.quintum.validator.CompareTwoFieldsValidator"
               method="validateTwoFields"
         methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionErrors,
                       javax.servlet.http.HttpServletRequest"
                  msg="errors.twoFields">
      </validator>

chenjianxiong
2004-03-19 14:58

application_zh.properties中定义的错误消息:

errors.twoFields={0}必须{1}{2}

怎么JDon现在发帖子时总会贴不上。害得我辛辛苦苦写的一段没有了:(:( faint.不写了。

kangkang
2004-03-20 16:04

This is another way.........

http://www.raibledesigns.com/page/rd/20030226#struts_validator_validating_two_fields

2Go 1 2 下一页