Conditional Bean Validation

二次信任 提交于 2019-12-02 08:02:37

Well I couldn't get into much depth in JSF annotation side, but I am curious why can't you simply call isValidActivationCode() in isAlreadyActivated() also i.e. something like below,

@AssertTrue(message="{invalidCode}")
private boolean isValidActivationCode() { ... }


@AssertTrue(message="{alreadyActivated}")
private boolean isAlreadyActivated() {

     if(isValidActivationCode()) {
           <Logic for isAlreadyActivated>
      )

}
Ravi K

As you said, if you feel workaround is not good one, then there are 2 options.

1) Go with same above workaround but make it bit more logical. Change return type of isAlreadyActivated() to Boolean instead of boolean. In isAlreadyActivated() method if isValidActivationCode() is false then return null.

http://docs.oracle.com/javaee/6/api/index.html?javax/validation/constraints/package-summary.html

As per above API, null are considered as valid. So your logic gets more clearer. true = valid, false = invalid, null = Not Applicable. You can put the same in javadoc for that method also.

 @AssertTrue(message="{invalidCode}")
    private boolean isValidActivationCode() { ... }


    @AssertTrue(message="{alreadyActivated}")
    private Boolean isAlreadyActivated() {

         if(isValidActivationCode()) {
               <Logic for isAlreadyActivated>
          } else {
             return null;
           }

    }

2) Go for custom constraint. @AssertTrue is built in constraint & jsf guys know that they are not enough. So they have given privilege to create your own. So go for that. Refer below links for the same.

http://docs.jboss.org/hibernate/validator/4.0.1/reference/en/html/validator-customconstraints.html

JSR 303 Validation, If one field equals "something", then these other fields should not be null

I think thats all we got, choice is yours :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!