struts1 validwhen驗證:
1.使用validwhen設計複雜的驗證
使用validwhen來設計複雜驗證的一個經常的要求就是根據一個字段驗證另外一個字段(比如, 如果你要用戶兩次輸入口令來確認值口令一致),另外一個就是表單中的一個字段只有另外一個字段有確定值的時候纔是必須輸入的。新的validwhen驗證規則將很快被包含在1.1後的STRUTS版本中,她就是用來處理這種情況的。
validwhen 規則處理單個的變量字段,叫測試。這變量的值是一個布爾的表達式,如果驗證有效則它必須爲真。可以包含這種變量的表達式有:
單引號或雙引號字符串literals,
十進制、十六進制、八進制的Integer literals,
null與null和空字符串匹配,
其它可以用屬性名引用的form字段,例如customerAge,
可以在外部因用得索引字段, 例如childLastName[2],
可以默認implicit因用得索引字段, 例如childLastName[], 她將作爲被索引的字段使用同樣的索引到數組中,
The literal *這裏指它包含當前測試字段的值,
作爲例子,考慮一個包含通訊地址和郵箱字段的form。如果通訊地址不爲空則郵箱字段是必須的required。你能這樣定義validwhen 規則:
<field property="emailAddress" depends="validwhen">
<arg0 key="userinfo.emailAddress.label"/>
<var>
<var-name>test</var-name>
<var-value>((sendNewsletter == null) or (*this* != null))</var-value>
</var>
</field>
上面定義的意思是:如果通訊地址是空或不空時這個字段時有效的。
2.使用validwhen驗證注意事項:
來源:http://www.nabble.com/Validation-framework...-weird...-td11777141.html
Balazs Michnay wrote:
> Dear Struts Users,
>
> I have a form with 13 form controls on it. I'd like to use the Struts Validation Framework to validate it, but it's acting weird.
> What I'd like to do is to have AT LEAST ONE of the controls filled, but the test of "validWhen" only allows simple boolean expressions.
> I used a simple approach of checking each control for their value being null but the test cannot containmore than one boolean operator.
> For instance, the following works just fine:
>
> <var>
> <var-name>test</var-name>
> <var-value> ((*this* != null) or (suly != null)) </var-value>
> </var>
>
> But if I insert another control test, I get an error message saying "ValidWhen Error for field ' magassag' - line 1:37: expecting RPAREN, found 'or'", so no more than two conditions are allowed in a test.
>
> Is that true? Is there any way to create complex tests? Or is there a way to validate the form for having at least one field filled?
The grammar for validwhen expressions is rather limited; you can only
have one operator per group. The solution is to add additional parentheses:
<var-value>(((*this* != null) or (suly != null)) or ...)/var-value>