开发者

JSR303 ConstraintValidator, how to show the message without an error page

Im working with JSF 2.0 and Glassfish v3. I was testing the functionality of JSR303 bean validation, so I created a validator which implements ConstraintValidator and then annotate that on a property wich I want to validate.

It works fine, but it displays a Glassfish default error page. I don't want this to be displayed, I would rather have the message displayed in a <h:outputText> or something.

Does anybody know how to achieve this?

Here is my validator method:

@Override
public boolean isValid(String searchArg, ConstraintVali开发者_开发问答datorContext ctx) {

    boolean searchArgCorrect = true;
    FacesMessage msg;
    if(searchArg!=null) {
        ctx.disableDefaultConstraintViolation();
        if(searchArg.length() < 3) {
            ctx.buildConstraintViolationWithTemplate("Searcharg is too short").addConstraintViolation();
            searchArgCorrect=false;

            msg = new FacesMessage(
                    FacesMessage.SEVERITY_ERROR,
                    "Searcharg is too short", null);

            throw new  ValidatorException(msg);
        }
    }

    return searchArgCorrect;
}

PS: I know that there are easier ways to validate the length of a string, but the above code snippet is only for demo/testing purposes. I have another plans with the validator.


You're mixing two concepts: JSF validation and JSR 303 bean validation. You're implementing JSR303 bean validation, but you're throwing a JSF-specific ValidatorException.

The method should not throw an exception. The method should just return true or false depending on the validation outcome. The message has to be definied in ValidationMessages.properties. JSF will then display it in a <h:message> which is associated with the input component.

See also this documentation on creating custom constraints with a message.


Or if you're actually after a standard JSF validator, then you should be implementing javax.faces.validator.Validator instead, annotate it with @FacesValidator and declare it in view by <f:validator>. It can throw a ValidatorException and the message will be displayed in <h:message> associated with the input component.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜