原文:http://struts.apache.org/2.2.1/docs/validation.html
There are two ways you can define validators in your -validation.xml file:
- <validator>
- <field-validator>
Keep the following in mind when using either syntax:
Non-Field-Validator: The <validator> element allows you to declare both types of validators (either a plain Validator a field-specific FieldValidator).
fiel d -validator : The <field-validator> elements are basically the same as the <validator> elements except that they inherit the fieldName attribute from the enclosing <field> element. FieldValidators defined within a <field-validator> element will have their fieldName automatically filled with the value of the parent <field> element's fieldName attribute. The reason for this structure is to conveniently group the validators for a particular field under one element, otherwise the fieldName attribute would have to be repeated, over and over, for each individual <validator>.
![]() | It is always better to defined field-validator inside a <field> tag instead of using a <validator> tag and supplying fieldName as its param as the xml code itself is clearer (grouping of field is clearer) |
![]() | Note that you should only use FieldValidators (not plain Validators) within a block. A plain Validator inside a <field> will not be allowed and would generate error when parsing the xml, as it is not allowed in the defined dtd (xwork-validator-1.0.2.dtd) |
Declaring a FieldValidator using the <field-validator> syntax
The choice is yours. It's perfectly legal to only use elements without the elements and set the fieldName attribute for each of them. The following are effectively equal:
译文:
非字段校验器vs字段校验器
这里有两种方法在你的-validation.xml文件里定义校验器
1.<validator>
2.<field-validator>
当你使用这两种方法时请将下面的禁忌于心。
非字段校验器:你可以使用<validator>标签定义两种类型的校验器(抽象出来的校验器或具体字段的校验器)
字段校验器:<field-validator>和<validator>只有一点不同, 那就是<field-validator>的
fieldName属性继承自他的父标签<field>标签。<field>标签通过制定name属性为他的子标签
绑定该指定字段,如:<field name="email_address"> 。采用这种结构的好处,很容易
把针对某一个字段的校验器集合到一个校验器组,否则的话你每个<validator>标签都要写一个
name属性,我的天啊。
在<field>标签下定义<field-validator>标签比在每一个<validator>标签下定义fieldname
参数更清晰。(字段组更清晰)
注意:你只能在field标签里面定义<field-validator>元素,而不能定义抽象的<validator>
元素。如果你在<field>标签里面定义<validator>将导致错误,因为这在 xwork-validator-1.0.2.dtd
是不允许的
在定义 字段校验器时请遵循以下语法规则:
你可以选择之一。你使用非字段校验,并且每一次都为他设定fieldname属性是完全合法的。
下面两种方式是一样的。
![]()
字段校验器:
一个<field>绑定一个字段,一个<field>可以有多个<field-validator>,对一个字段可以有多个校验。
结构清晰,方便浏览和检查。易于维护。
非字段校验器:
一个<validator>标签下面只能对一个字段进行校验,如果对一个字段进行多次校验,需要写很多个<validator>,很繁琐。而且不利于维护。
by loverszhaokai