validationstruts2xwork

Reusing a regex in XWork validator


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?


Solution

  • 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.