Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1967134
  • 博文数量: 606
  • 博客积分: 9991
  • 博客等级: 中将
  • 技术积分: 5725
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-17 19:07
文章分类

全部博文(606)

文章存档

2011年(10)

2010年(67)

2009年(155)

2008年(386)

分类:

2008-07-20 13:11:10

1. 文件结构

       validation.xml文件的文档结构是由validator_1_1_3.dtd文件定义,其文件头部内容如下:

          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"

          "">

       其顶层元素为:,它包含子元素。一般只需要定义元素,元素定义格式如下:

       其中为可选子元素,而

子元素至少需要出现一次。子元素的定义格式如下:

..............

       其中属性描述如下:

l         name:指定了表单的名字与配置文件中的form-beanname相同;

l          field:对应表单中验证的字段;

l          property:对应ActionForm的属性;

l          depends:指定验证规则,例如:requiredmaxlength等;

l          pageActionForm若是跨页表单,则与表单中的page属性对应。

2. 子元素配置举例

2.1 必填(或非空)验证

       非空验证的depends属性值为required,配置举例如下:

        

                  

        

        

                  

        

        

                  

        

其中中的key跟资源文件中的键对应。

注意:为了使默认的验证产生正确的信息,开发人员还需要在资源文件中添加errors.required等默认的错误信息,具体操作时,开发人员可在简体中文的资源文件:ApplicationResources_zh_CN.properties.bak中添加如下信息:

errors.required = {0}不能为空

errors.maxlength = {0}长度不能大于{1}个字符

errors. minlength = {0}长度不能小于{1}个字符

errors.short = {0}必须是一个整数

errors.integer = {0}必须是一个整数

errors.long={0}必须是一个整数

errors.float={0}必须是一个浮点数

errors.double ={0}必须是一个双精度型

errors.date={0}必须是一个日期

errors.range = {0}必须是 {1} {2}之间的整数

errors.creditcard={0}必须是一个有效的信用卡号码

errors.email = {0}是无效e-mail地址

在英文资源文件ApplicaitonResources.properties中添加如下内容:

errors.required={0} is required.

errors.minlength={0} can not be less than {1} characters.

errors.maxlength={0} can not be greater than {1} characters.

errors.invalid={0} is invalid.

        

errors.byte={0} must be a byte.

errors.short={0} must be a short.

errors.integer={0} must be an integer.

errors.long={0} must be a long.

errors.float={0} must be a float.

errors.double={0} must be a double.

        

errors.date={0} is not a date.

errors.range={0} is not in the range {1} through {2}.

errors.creditcard={0} is an invalid credit card number.

errors.email={0} is an invalid e-mail address.

2.2 最大长度和最小长度验证

       可在元素的depends属性中添加maxlengthminlength来限制对于那个字段的最大长度和最小长度,使用举例如下:

maxlength

12

minlength

6

2.3 Email验证

       Struts中还可以添加email验证,此时dependsemail,使用举例如下:

2.4 日期验证

       Struts中还可以添加日期验证,此时dependsdate,使用举例如下:

2.5 整数范围验证

       Struts中还提供了验证整数是否在某个范围之间,例如下述的例子验证整数是否在19999之间,配置如下:

min

1

max

99999

2.6 自定义验证

Struts中的验证机制提供了扩展,开发人员可以添加自定义的验证规则,例如可添加文件类型的验证。此时需要编写的Java类、在validator-rules.xml添加该验证规则以及添加验证的js

自定义验证的JavaCustomValidator的代码如下所示:

package com.amigo.struts.validation;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

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;

/**

 * Struts自定义验证类.

 */

public class CustomValidator {

        

         /**

          * 判断文件类型

          */

         public static boolean validateFileType(Object bean, ValidatorAction va,

                            Field field, ActionMessages errors, Validator validator,

                            HttpServletRequest request) {

                   String value = ValidatorUtils.getValueAsString(bean, field

                                     .getProperty());

                   String inputType = value.substring(value.lastIndexOf('.'));

                   String type[] = field.getVarValue("fileTypeProperty").split(";");

                   if (!GenericValidator.isBlankOrNull(value)) {

                            try {

                                     boolean judge = false;

                                     for (int i = 0; i < type.length; i++) {

                                               Pattern p = Pattern.compile(type[i],

                                                                 Pattern.CASE_INSENSITIVE);

                                               Matcher m = p.matcher(inputType);

                                               judge = m.matches();

                                               if (judge) {

                                                        break;

                                               }

                                     }

                                    

                                     if (!judge) {

                                               errors.add(field.getKey(), Resources.getActionMessage(

                                                                 validator, request, va, field));

                                               return false;

                                     }

                            } catch (Exception e) {

                                     errors.add(field.getKey(), Resources.getActionMessage(

                                                        validator, request, va, field));

                                     return false;

                            }

                   }

                   return true;

         }

}

       接着还需要在validator-rules.xml这个验证规则文件中添加如下内容:

                            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"

                            msg="errors.fileType">

                           

                                    

 function validateFileType(form) {

        var isValid = true;

        var focusField = null;

        var i = 0;

        var fields = new Array();

        var formName = form.getAttributeNode("name");

                  

       oFileType = eval('new ' + formName.value + '_fileType()'); 

       

      

     

        for (x in oFileType) {

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

                           

           

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

                field.type == 'text' ||

                field.type == 'file' ||

                field.type == 'textarea') &&

                field.disabled == false) {

                           

             var iMax =oFileType[x][2]("fileTypeProperty").split(";");

             var index = field.value.lastIndexOf(".");

          var length = field.value.length;

                  var fileType= field.value.substring(index, length);

                  var judege=false;

                

                 if(length>0 && fileType!=""){

         for (var j = 0; j < iMax.length; j++) {

            if (iMax[j].toLowerCase() == fileType.toLowerCase()) {

                judege = true;

                break;

            }

                  }

                

            if (!judege) {

            if (i == 0) {

                        focusField = field;

                    }

          

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

                    isValid = false;

                }

                }

            }

        }

        if (fields.length > 0) {

           focusField.focus();

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

        }

        return isValid;

    }

    ]]>

                           

                  

              利用上面这个自定义的验证可以验证文件的类型,在下面的例子中验证文件的类型是否为jpg的,举例如下:

        

        

                   fileTypeProperty

                   .jpg

        

3.  完整配置实例

       本小节举一个validation.xml配置的完整例子,本例汇总,对两个表单添加了验证规则。内容如下:

          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"

          "">

        

                  

                           

                                    

                           

                           

                                    

                           

                           

                                    

                                    

                                    

                                               maxlength

                                               200

                                    

                           

                  

                  

                           

                                    

                           

                           

                                    

                           

                           

                                    

                           

                  

        

阅读(1453) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~