javax.validation.validationException:必须至少创建一条自定义消息



根据hibernate中编写的checkCase约束验证器JSR 303 chackCase contrintValidator

public boolean isValid(Group group, ConstraintValidatorContext constraintValidatorContext) {
    boolean isValid = false;
    ...
    if(!isValid) {
        constraintContext.disableDefaultConstraintViolation();
        constraintValidatorContext
            .buildConstraintViolationWithTemplate( "{my.custom.template}" )
            .addNode( "myProperty" ).addConstraintViolation();
    }
    return isValid;
}

使用<f:validateBean>在JSF中应用此验证器将导致以下异常:
javax.validation.validationException:如果在使用此验证器时禁用默认错误消息,则必须至少创建一个自定义消息

package com.mycompany;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {
    private CaseMode caseMode;
    public void initialize(CheckCase constraintAnnotation) {
        this.caseMode = constraintAnnotation.value();
    }
    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
        if (object == null)
            return true;
        if (caseMode == CaseMode.UPPER)
            return object.equals(object.toUpperCase());
        else
            return object.equals(object.toLowerCase());
    }
}


如果没有constraintValidatorContext,将在<h:messages> 中发出消息

问题是,验证器中的validate((返回false,但没有创建任何消息。你必须添加一个这样的:

if (some condition) {
    constraintContext.buildConstraintViolationWithTemplate("something is wrong")
            .addConstraintViolation();
    return false;
}
return true;

相关内容

  • 没有找到相关文章