How to validate Boolean fields in Struts2 using annotations?

1.1k views Asked by At

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.

1

There are 1 answers

3
Roman C On BEST ANSWER

You can do this using @FieldExpressionValidator. For example

@Validations(fieldExpressions = @FieldExpressionValidator(fieldName="boolField", expression="boolField == true", message="boolField should be set"))