在 Struts 2 中我们可以开发 @CustomValidator
可以在应用范围内使用
In Struts 2 we can develop @CustomValidator
which can be used in application wide
@CustomValidator(type = "CustomerNumberValidator", fieldName = "customerNo")
为了验证更多,我们使用@ExpressionValidator
@ExpressionValidator(expression =
"( (!''.equals(account.firstName) && (!''.equals(account.lastName) )
|| (presonalAccount == false)",
key = "validate.account.name")
如果表达式太复杂,需要处理更多个字段,我们使用OGNL调用静态方法.静态方法将进行验证并返回一个 boolean
例如
If the expression is too complicated and needs to work on more than one field we use OGNL to call the static method. The static method will do the validation and return a boolean
for example
@ExpressionValidator(expression = "@foo.bar.CalendarUtil@compareDates(fromDate,toDate)", key = "validate.date.before")
以上是自定义表达式验证器的一些方法!
Above is some how a Custom Expression Validator !
我们在应用程序范围内使用 @foo.bar.CalendarUtil@compareDates
为我们进行此验证.
And we use @foo.bar.CalendarUtil@compareDates
in application wide to make this validation for us.
还有其他方法可以让我们使用自定义范围验证器吗?!
Is there another approach which enables us to use a custom wide validator?!
是否有任何自定义表达式验证器可以添加到 Struts 中,我们可以像使用 @CustomValidator
一样在 Action
中调用它?
Is there any custom expression validator which can be added to Struts and we can call it in Action
in the way we use @CustomValidator
?
创建自定义验证器(与字段无关):
Create a Custom Validator (not field related):
public final class CompareDatesValidator extends ValidatorSupport {
private String fromDate; // getter and setter
private String toDate; // getter and setter
@Override
public void validate(Object o) throws ValidationException {
Date d1 = (Date)parse(fromDate, Date.class);
Date d2 = (Date)parse(toDate, Date.class);
if (d1==null || d2==null || d2.before(d1)){
addActionError(getDefaultMessage());
}
}
}
在 validators.xml
文件中注册自定义验证器:
Register the custom validator in validators.xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
<validator name="compareDatesValidator"
class="org.foo.bar.CompareDatesValidator"/>
</validators>
在操作中使用验证器:
private Date startDate; // getter and setter
private Date endDate; // getter and setter
@Validations(
customValidators={
@CustomValidator(type="compareDatesValidator",
message="Dates provided are not valid."
parameters={
@ValidationParameter(name="fromDate", value="${startDate}"),
@ValidationParameter(name="toDate", value="${endDate}")})})
public String execute(){
return SUCCESS;
}
这篇关于在 Struts 2 中重用自定义表达式验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!