文:阿蜜果
日期:2008-1-2——1-3
1. 文件结构
validation.xml文件的文档结构是由validator_1_1_3.dtd文件定义,其文件头部内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
其顶层元素为:<form-validation>,它包含<formset>和<global>子元素。一般只需要定义<formset>元素,<formset>元素定义格式如下:
<formset>
<constant></constant>
<form></form>
</formset>
其中<constant />为可选子元素,而<form />子元素至少需要出现一次。<form />子元素的定义格式如下:
<form name="">
<field property=""></field>
..............
<field property="" depends="" page="" indexedListProperty=""></field>
</form>
其中属性描述如下:
l name:指定了表单的名字与配置文件中的form-bean的name相同;
l field:对应表单中验证的字段;
l property:对应ActionForm的属性;
l depends:指定验证规则,例如:required、maxlength等;
l page:ActionForm若是跨页表单,则与表单中的page属性对应。
2. <field>子元素配置举例
2.1 必填(或非空)验证
非空验证的depends属性值为required,配置举例如下:
<form name="UserForm">
<field property="loginName" depends="required">
<arg0 key="UserForm.loginName" />
</field>
<field property="name" depends="required">
<arg0 key="UserForm.name" />
</field>
<field property="password" depends="required">
<arg0 key="UserForm.password" />
</field>
</form>
其中<arg0 key="UserForm.password" />中的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 最大长度和最小长度验证
可在<field>元素的depends属性中添加maxlength和minlength来限制对于那个字段的最大长度和最小长度,使用举例如下:
<field property="password" depends = "required, maxlength, minlength">
<arg0 key = "UserForm.password"/>
<var>
<var-name>maxlength</var-name>
<var-value>12</var-value>
</var>
<var>
<var-name>minlength</var-name>
<var-value>6</var-value>
</var>
</field>
2.3 Email验证
在Struts中还可以添加email验证,此时depends为email,使用举例如下:
<field property="email" depends="required, email">
<arg0 key="UserForm.email" />
</field>
2.4 日期验证
在Struts中还可以添加日期验证,此时depends为date,使用举例如下:
<field property="begintime" depends="date">
<arg0 key="HistoryForm.begintime" />
</field>
2.5 整数范围验证
在Struts中还提供了验证整数是否在某个范围之间,例如下述的例子验证整数是否在1到9999之间,配置如下:
<field property="score" depends="intRange">
<arg0 key="TestForm.score" />
<arg1 name="intRange" key="${var:min}" resource="false" />
<var>
<var-name>min</var-name>
<var-value>1</var-value>
</var>
<arg2 name="intRange" key="${var:max}" resource="false" />
<var>
<var-name>max</var-name>
<var-value>99999</var-value>
</var>
</field>
2.6 自定义验证
在Struts中的验证机制提供了扩展,开发人员可以添加自定义的验证规则,例如可添加文件类型的验证。此时需要编写的Java类、在validator-rules.xml添加该验证规则以及添加验证的js。
自定义验证的Java类CustomValidator的代码如下所示:
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这个验证规则文件中添加如下内容:
<!-- 判断文件类型-->
<validator name="fileType" classname="com.cotel.comm.EarlyValidator" method="validateFileType"
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">
<javascript>
<![CDATA[
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;
}
]]>
</javascript>
</validator>
利用上面这个自定义的验证可以验证文件的类型,在下面的例子中验证文件的类型是否为jpg的,举例如下:
<field property="picPath" depends="required,fileType">
<arg0 key="TestForm.picPath" />
<var>
<var-name>fileTypeProperty</var-name>
<var-value>.jpg</var-value>
</var>
</field>
3. 完整配置实例
本小节举一个validation.xml配置的完整例子,本例汇总,对两个表单添加了验证规则。内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<formset>
<form name="UserinfoForm">
<field property="email" depends="email">
<arg0 key="UserinfoForm.email" />
</field>
<field property="mobile" depends="required">
<arg0 key="UserinfoForm.mobile" />
</field>
<field property="description" depends="maxlength">
<arg0 key="UserinfoForm.description" />
<arg1 name="maxlength" key="${var:maxlength}" resource="false" />
<var>
<var-name>maxlength</var-name>
<var-value>200</var-value>
</var>
</field>
</form>
<form name="PasswordForm">
<field property="newPass" depends="required">
<arg0 key="PasswordForm.newPass" />
</field>
<field property="oldPass" depends="required">
<arg0 key="PasswordForm.oldPass" />
</field>
<field property="conPass" depends="required">
<arg0 key="PasswordForm.conPass" />
</field>
</form>
</formset>
</form-validation>
posted on 2008-01-05 12:37
阿蜜果 阅读(8708)
评论(2) 编辑 收藏 所属分类:
Struts