8.2. Validating Using Regular Expressions

Problem

You want to validate data using a regular expression.

Solution

Use the mask validation type provided by the Validator:

<form name="ValidationTestForm">
    <!-- Validate Social Security Number -->
    <field property="ssn"
            depends="required,mask">
        <arg key="prompt.ssn"/>
        <var>
            <var-name>mask</var-name>
            <var-value>^[0-9]{3}-[0-9]{2}-[0-9]{4}$</var-value>
        </var>
    </field>
</form>

Discussion

A regular expression uses a general pattern notation that can be used to describe and parse text. Regular expressions have been around in one form or another since the 1960s. Using regular expressions, you can validate that a user's input matches a specific pattern. The pattern, simple or complex, is specified as a mask value that uses the regular expression pattern language. Without regular expressions, you would have to write a significant amount of custom code. Despite the power of regular expressions, many developers aren't comfortable using them. If you don't know regular expressions, learn them now because it could change your life. A good place to start is Mastering Regular Expressions by Jeffrey E. F. Friedl (O'Reilly).

The Validator supports the use of regular expressions through the mask bundled validator. A validation passes if the field value matches a given regular expression. You specify the regular expression through a Validator variable, defined in a var element. The name of the variable must be mask, and the value is the regular expression to ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.