Amit Khanna
Amit Khanna

Reputation: 489

Struts 2 validate field if not empty

There are two fields email and phone number (integer) in a form. The form is validated using the struts validation framework (ActionClass-validation.xml). These two fields are optional, so the user can leave them blank. But if they are not blank the fields need to be validated. Please help me find out how to write validators in xml to do this.

Upvotes: 2

Views: 4017

Answers (2)

coding_idiot
coding_idiot

Reputation: 13734

Try this

<field name="email">
    <field-validator type="email">
        <message>Invalid Email (empty email accepted)</message>
    </field-validator>
</field>

<field name="contact">
     <field-validator type="regex">
       <param name="expression"><![CDATA[([1234567890]+)]]></param>
       <message>Invalid Contact Number (empty number accepted)</message>
    </field-validator>
</field>

Here is a complete example.

Upvotes: 1

loscuropresagio
loscuropresagio

Reputation: 1952

You can also use annotations. In my opinion it's more clear to understand and easy to write and debug. This is an example:

@EmailValidator(type = ValidatorType.SIMPLE, message = "", key = "validation.email")
public String getEmail() {
  return email;
}

For the number, you can use a regex validator:

@RegexFieldValidator(key = "validation.number", message = "", type = ValidatorType.SIMPLE, expression = NUMBER_PATTERN_STRING)
public String getNumber() {
  return number;
}

In your jsp you can reference the errors using field (or action) error tags:

<s:fielderror fieldName="email" cssClass="myerrorclass"/>
<s:textfield  name="email" cssClass="myclass" cssErrorClass="myothererrorclass"/>

I hope the code is quite self-explanatory. Happy coding! ;)

Upvotes: 4

Related Questions