正文

Validator 验证 - 自定义验证2007-03-13 11:07:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/hurongliang/23926.html

分享到:

n  struts1.1中创建一个自定义的验证,验证一个字段的值是否和另一个字段的值相等。

1.  创建一个包含一个实现规则接口的静态方法的类。

CunstomValidatorRules.java;

package com.oreilly.strutsckbk.ch08;

 

import javax.servlet.http.HttpServletRequest;

 

import org.apache.commons.validator.Field;

import org.apache.commons.validator.GenericValidator;

import org.apache.commons.validator.ValidatorAction;

import org.apache.commons.validator.util.ValidatorUtils;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.validator.Resources;

 

public class CustomValidatorRules {

   

    public static boolean validateTwoFields( Object bean,

                                             ValidatorAction va,

                                             Field field,

                                             ActionErrors errors,

                                             HttpServletRequest

                                             request ) {

        String value = ValidatorUtils.getValueAsString(bean, field.getProperty( ));//得到字段名的方法1

        String sProperty2 = field.getVarValue("secondProperty");//得到字段名的方法2

        String value2 = ValidatorUtils.getValueAsString(bean,

                        sProperty2);//得到字段的值的方法

       

        if (!GenericValidator.isBlankOrNull(value)) {

            try {

                if (!value.equals(value2)) {

                    errors.add(

                            field.getKey( ),

                            Resources.getActionError(request, va, field));

                    return false;

                }

            } catch (Exception e) {

                errors.add(

                        field.getKey( ),

                        Resources.getActionError(request, va, field));

                return false;

            }

        }

 

        return true;

    }

}

2.  validator-rules.xml中在global元素下添加validator子元素:

validator-rules.xml:

<validator name="twofields"

      classname="com.oreilly.strutsckbk.ch08.CustomValidatorRules"

         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"

        depends="required"

            msg="errors.twofields">

    <javascript><![CDATA[

    function validateTwoFields(form) {

        var bValid = true;

        var focusField = null;

        var i = 0;

        var fields = new Array( );

        oTwoFields = new twofields( );

        for (x in oTwoFields) {

            var field = form[oTwoFields[x][0]];

            var secondField = form[oTwoFields[x][2]("secondProperty")];

        

            if (field.type == 'text' ||

                field.type == 'textarea' ||

                field.type == 'select-one' ||

                field.type == 'radio' ||

                field.type == 'password') {

       

                var value;

                var secondValue;

                // get field's value

                if (field.type == "select-one") {

                    var si = field.selectedIndex;

                    value = field.options[si].value;

                    secondValue = secondField.options[si].value;

                } else {

                    value = field.value;

                    secondValue = secondField.value;

                }

           

                if (value != secondValue) {

               

                    if (i == 0) {

                        focusField = field;

                    }

                    fields[i++] = oTwoFields[x][1];

                    bValid = false;

                }

            }

        }

         

        if (fields.length > 0) {

            focusField.focus( );

            alert(fields.join('\n'));

        }

           

        return bValid;

    }]]></javascript>

</validator>

3.  资源属性文件中添加error.twofields信息。

ApplicationResources.properties:

errors.twofields={0} must be equal to {1}.

4.  要使用这个验证规则,需要在validation.xml中进行配置:

validation.xml:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE form-validation PUBLIC

          "-//Apache Software Foundation//DTD Commons Validator Rules

          Configuration

          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">

<form-validation>

    <formset>

        <form name="RegistrationForm">

            <field property="emailAddress"

                    depends="required,email">

                <arg0 key="prompt.emailAddress"/>

            </field>

            <field property="password"

                    depends="required">

                <arg0 key="prompt.password"/>

            </field>

            <field property="password2"

                    depends="required,twofields">                

                <arg0 key="prompt.password2"/>

                <arg1 key="prompt.password"/>

                <var>

                    <var-name>secondProperty</var-name>

                    <var-value>password</var-value>

                </var>

            </field>

        </form>

    </formset>

</form-validation>

n  创建自定义类的时候用于验证的方法名必须是validator<ruleName>,开头为validator后跟验证规则名称。

struts1.1中的此方法如下声明:

public static boolean validateRuleName( Object bean,

                                        ValidatorAction va,

                                        Field field,

                                        ActionErrors errors,

                                        HttpServletRequest request)

这个方法返回一个布尔值,表示是否通过验证。方法参数说明如下:

 

Name

Type

Purpose

bean

Object

The ActionForm being validated. You retrieve the input values from this object's properties.

Va

ValidatorAction

Object representation of the pluggable validator element from the validator-rules.xml file for the particular rule. Used to generate the error message for the rule.

field

Field

Object representation of the field element from the validation.xml file. Provides access to the nested variables (var) and arguments (arg).

errors

ActionErrors

An instance of ActionErrors you populate with ActionError objects. For Struts 1.2, this variable is an ActionMessages instance that you populate it ActionMessage objects.

request

HttpServletRequest

The HTTP servlet request. Used by the Resources utility class to retrieve the MessageResources for creating an ActionError.

 

此方法的执行过程如下:

1)   ActionForm中获得要验证的字段值。

2)   secondProperty变量中获取被比较的字段名称。

3)   ActionForm中获得用secondProperty指定的变量的值。

4)   检查要验证的字段的值是否为NULL或空字符串。如果是,则返回true,否则继续执行。

5)   equals()方法比较两个字段值是否相等。

6)   如果不等,将一个错误ActionError添加到errors中并返回false

7)   如果在56步中有异常抛出则添加ActionErrorerrors中并返回false

8)   如果没有异常抛出则验证通过返回true

n  创建了自定义的验证类后需要在validator-rules.xml中配置验证规则:

<validator name="twofields"

      classname="com.oreilly.strutsckbk.ch08.CustomValidatorRules"

         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"

        depends="required"

            msg="errors.twofields">

name属性指定验证规则的名称。

className属性阵地自定义的验证类。

methodParams指定验证类的参数类型。如果你使用struts1.2,请将ActionErrors改成ActionMessages

depends表示这个自定义的类依赖与哪个验证规则,在这里,他依赖于required,意思是,当在validation.xml中对字段要求进行twofield验证时,验证框架先根据validator-rules.xml执行对应validtor元素的depends指定的验证规则。在这里验证twofields时先进行required验证,如果required验证失败,则不执行twofields验证,只有当requierd验证通过是才进行twofields验证。因此,此例中validtion.xml里对password2的验证只须一个twofields即可。

JS脚本跟JAVA类一样起作用,命名也相同(validate<ruleName>),他必须返回一个boolean值表示是否通过验证。

阅读(5770) | 评论(6)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

loading...
您需要登录后才能评论,请 登录 或者 注册