一 form表單必須要實現繼承validateForm
並且不能實現validate方法
不然會默認使用validate方法驗證
package com
jinchun
struts
form;
import javax
servlet
http
HttpServletRequest;
import org
apache
struts
action
ActionErrors;
import org
apache
struts
action
ActionMapping;
import org
apache
struts
validator
ValidatorForm;
public class LoginForm extends ValidatorForm {
private String sex;
public void reset(ActionMapping mapping
HttpServletRequest request) {
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this
sex = sex;
}
}
}
二
使用validator_rules
xml新建validation
xml文件作為驗證規則文件
<!DOCTYPE form
validation PUBLIC
//Apache Software Foundation//DTD Commons Validator Rules Configuration
//EN
_
_
_
dtd
>
<form
validation>
<formset>//裡面可以驗證多個表單
<form name=
loginForm
>//驗證loginForm表單
這個表單名稱和//nfig
xml文件中的表單名稱相對應
<field property=
uname
depends=
required
mask
>//驗證必填和規則兩項
<arg
key=
namelab
/>
<var>
<var
name>mask</var
name>
<var
value>[A
Za
z]</var
value>
</var>
</field>
<field property=
age
depends=
required
intRange
>//驗證必填和范圍
項
<arg
key=
agelab
/>
<arg
name=
intRange
key=
${var:min}
resource=
false
/>
<arg
name=
intRange
key=
${var:max}
resource=
false
/>
<var>
<var
name>min</var
name>
<var
value>
</var
value>
</var>
<var>
<var
name>max</var
name>
<var
value>
</var
value>
</var>
</field>
</form>
</formset>
</form
validation>
三 資源文件裡面如下
ApplicationResources
properties
# Resources for parameter
com
jinchun
struts
ApplicationResources
# Project struts_validate
namelab=姓名
errors
required=<font size=
color=red>{
}是必須填的</font>//對應必填
errors
range=<font size=
color=red>{
}是必須在{
}和{
}之間的</font>//對//應范圍
agelab=年齡
errors
invalid=<font size=
color=red>{
}是無效的</font>//對應mask
sexlab=性別
tellab=電話
emaillabe=email地址
四 struts
config
xml文件中
<message
resources
parameter=
com
jinchun
struts
ApplicationResources
/>
<plug
in className=
org
apache
struts
validator
ValidatorPlugIn
>
<set
property property=
pathnames
value=
/WEB
INF/validator
rules
xml
/WEB
INF/validation
xml
/>
</plug
in>//這句話是從validator
rules
xml中復制的
</struts
config>
From:http://tw.wingwit.com/Article/program/Java/ky/201311/27908.html