如果使用ValidatorForm 和validate 方法,两个或多个字段的验证太容易了。
要使用声明式自定义验证器,您需要阅读 this 参考指南,该指南包含用于验证两个字段的自定义验证器链接和示例。
这是一个如何比较两个字段以查看它们是否具有相同值的示例。一个很好的例子是当您验证用户更改密码时,有主密码字段和确认字段。
<validator name="twofields"
classname="com.mysite.StrutsValidator"
method="validateTwoFields"
msg="errors.twofields"/>
<field property="password"
depends="required,twofields">
<arg position="0" key="typeForm.password.displayname"/>
<var>
<var-name>secondProperty</var-name>
<var-value>password2</var-value>
</var>
</field>
public class CustomValidator {
// ------------------------------------------------------------ Constructors
/**
* Constructor for CustomValidator.
*/
public CustomValidator() {
super();
}
// ---------------------------------------------------------- Public Methods
/**
* Example validator for comparing the equality of two fields
*
* http://struts.apache.org/userGuide/dev_validator.html
* http://www.raibledesigns.com/page/rd/20030226
*/
public static boolean validateTwoFields(
Object bean,
ValidatorAction va,
Field field,
ActionMessages errors,
HttpServletRequest request) {
String value =
ValidatorUtils.getValueAsString(bean, field.getProperty());
String property2 = field.getVarValue("secondProperty");
String value2 = ValidatorUtils.getValueAsString(bean, property2);
if (!GenericValidator.isBlankOrNull(value)) {
try {
if (!value.equals(value2)) {
errors.add(
field.getKey(),
Resources.getActionMessage(request, va, field));
return false;
}
} catch (Exception e) {
errors.add(
field.getKey(),
Resources.getActionMessage(request, va, field));
return false;
}
}
return true;
}
}