1

Given a Boolean field in an action class like so.

@Namespace("/admin_side")
@ResultPath("/WEB-INF/content")
@ParentPackage(value="struts-default")
public final class TestAction extends ActionSupport implements Serializable, ValidationAware, ModelDriven<Entity>
{
    private Boolean boolField;

    public Boolean getBoolField()
    {
        return boolField;
    }

    public Boolean setBoolField(Boolean boolField)
    {
        this.boolField=boolField;
    }

    @Validations(requiredFields={@RequiredFieldValidator(fieldName="boolField", type= ValidatorType.FIELD, key="delete.row.confirm")})
    @Action(value = "testAction",
            results = {
                @Result(name=ActionSupport.SUCCESS, type="redirectAction", location="Test.action"),
                @Result(name = ActionSupport.INPUT, location = "Test.jsp")},
    public String testAction()
    {            
        return ActionSupport.SUCCESS;
    }

    // The rest of the action class.
}

The field in the action class boolField should be validated only when it is set to true. It may be a hidden field <s:hidden> or it may be set via a query-string parameter.

This and this questions use XML configurations for boolean field validation but do not say anything about annotations.

How to validate such boolean fields using annotations?

I have avoided interceptors and other things to make the code shorten.

Community
  • 1
  • 1
Tiny
  • 27,221
  • 105
  • 339
  • 599

1 Answers1

2

You can do this using @FieldExpressionValidator. For example

@Validations(fieldExpressions = @FieldExpressionValidator(fieldName="boolField", expression="boolField == true", message="boolField should be set"))
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • It validates a `Boolean` type field, when its value is set to `true`. but when the `Boolean` type field in an action class is set to `false`, it causes the [`java.lang.NullPointerException`](http://pastebin.com/YA8a4Y0T) to be thrown event though there is also a `@RequiredFieldValidator` for that field. – Tiny Jan 03 '14 at 15:29
  • This is because the value is not `null`. See updates. – Roman C Jan 03 '14 at 17:03
  • Oh yes! Indeed that I did not notice. Silly me :). – Tiny Jan 04 '14 at 03:27