根据hibernate编写的checkCase约束验证器JSR 303 chackCase contraintValidator
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>