struts2 conditional xml validation

2019-07-31 10:49发布

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.

2条回答
我命由我不由天
2楼-- · 2019-07-31 11:10

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.

查看更多
时光不老,我们不散
3楼-- · 2019-07-31 11:23

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.

查看更多
登录 后发表回答