首先搭建好struts1的开发环境,然后在struts1的配置文件struts-config中加入
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/org/apache/struts/validator/validator-rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>
这样就把Validator插件引入到struts1中了,然后新建一个UserFormBean继承ValidateActionForm类
package cn.lfd.web.formbean;
import org.apache.struts.chain.commands.servlet.ValidateActionForm;
public class UserFormBean extends ValidateActionForm {
private String username;
private String password;
private String email;
private String birthday;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
然后在WEB-INF目录下新建一个validation.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">
<form-validation>
<formset>
<form name="UserFormBean">
<field property="username" depends="required,minlength,maxlength">
<arg key="用户名" position="0" resource="false"/>
<arg name="minlength" key="${var:minlength}" position="1" resource="false"/>
<arg name="maxlength" key="${var:maxlength}" position="1" resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>3</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>8</var-value>
</var>
</field>
<field property="email" depends="email">
<arg key="邮箱" position="0" resource="false"/>
</field>
</form>
</formset>
</form-validation>
校验器从validator-rules.xml文件中可以获取,最后新建一个MessageResource.properties的资源文件,在struts-config文件中配置一下,struts1就会根据这个文件进行错误显示
<message-resources parameter="MessageResource"></message-resources>
MessageResource.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.