1

Without making a new class and adding it as a validator type, I'd like to reuse some regular expressions in XWork.

I cannot seem to find a tutorial online with the proper syntax. I'd like to change the following:

<field name="example">
    <field-validator type="regex">
       <param name="expression">[some ridiculously long regex expression like](0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)</param>
       <message key="example.error" />
    </field-validator>
</field>

to something like:

 <regex-pattern>
   <name>date-regex-pattern</name>
   <expression>[some ridiculously long regex expression like](0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)</expression>
 </regex-pattern>

<field name="example">
    <field-validator type="regex">
       <param name="expression">{date-regex-pattern}</param>
       <message key="example.error" />
    </field-validator>
</field>

Or create a new field-validator type in xml by chaining other existing types, e.g., a required field with minimum and maximum lengths and a regex to pass.

What is the proper location for the xml and syntax in XWork?

tzimnoch
  • 216
  • 1
  • 13
  • Using regex for date validation isn't the best idea. – Aleksandr M Jun 17 '14 at 10:46
  • Nevertheless, reusing regex validators by giving them names is a useful pattern I would like to know how is accomplished with XWork. Struts 1 had global constants in validation xml files. – tzimnoch Jun 17 '14 at 15:25

1 Answers1

1

Put your expression once in a String exposed by a getter method in your BaseAction (the Action extended by all the others):

private final static ridiculouslyLongRegexExpression 
                  = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";

public getRidiculouslyLongRegexExpression(){
    return ridiculouslyLongRegexExpression;
}

Then call it from your XML files using regexExpression:

<field name="example">
    <field-validator type="regex">
        <param name="regexExpression">${ridiculouslyLongRegexExpression}</param> 
    </field-validator>
</field>

More info on the official documentation.

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • Thank you. I suppose this is one way to go about reusing regex's. Do you know if XWork just doesn't support this sort of feature directly in the validation xml files? – tzimnoch Jun 17 '14 at 15:29
  • No, because while XML files can access the action, it can't access nor "extend" other XML files... then it would not be reusable. – Andrea Ligios Jun 17 '14 at 15:45