struts2 conditional xml validation

我们两清 提交于 2019-12-13 02:17:56

问题


I have what I'd think is a common issue but an entire day of googling hasn't turned up anything useful.

I have a form with a checkbox and a textfield. I'd like to do a regex validation of the textfield, but only if the checkbox is selected. Regex validation is currently working for other non-conditional fields but I can't for the life of me figure out if there is a syntax that allows for this in the action-validation.xml file. ie. I have something like below for other fields. What I need is a way of making this conditionaly evaluated only if the checkbox is selected.

<validators>
 <field name="sn">
  <field-validator type="regex" >
   <param name="expression">
    [0-9]{12} 
                   </param>
   <message>Serial number format is invalid. Please try again</message>
  </field-validator>
 </field>
</validators>

Does anyone have a code example of how to do this?

Any help is much appreciated.


回答1:


For Struts 1 there was a validation rule called "validwhen" that you could use to perform complex validations, but for Struts 2, as far as I know there is no such validation.

For Struts 2 you could go with the Expression Validator in which you can specify an OGNL expression to use, so I guess you could try something like this:

<validator type="expression">
    <param name="expression">checkboxField eq "selected" and inputText eq "bla"</param>
    <message>....</message>
</validator>

One thing I don't know is if there is a easy way of doing your regular expression check using OGNL (you'll have to look into it).

Additionally, if that does not work, you can always write your own custom validator.




回答2:


The expression and fieldexpression validators take an OGNL expression. Evaluating to true passes false fails. You can use them quite easily for this requirement.

Personally I would just use the built in validators via XML like you're doing and then implement any custom validation logic in the validate() method (or methodname-validate() method). Just preference, no good reason really.



来源:https://stackoverflow.com/questions/4553330/struts2-conditional-xml-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!