Search code examples
javahibernate-validator

How to apply hibernate validation to Character type?


@Pattern(regexp = "^[M|F]{1}$", message ="Must be M or F")
private Character gender;

Result:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: java.lang.Character.

How can achieve the following:

  • apply hibernate validation to the character using a regex pattern
  • restricting the return type to be a single letter (that's why I chose char)
  • to everything of this in a single method?

Solution

  • I had similiar problem and i didnt find any default hibernate validator annotation for that. But there is easy way to create custom annotation. (look here https://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/validator-customconstraints.html) Below example with sex:

    @Target({ METHOD, FIELD, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    @Constraint(validatedBy = SexValidator.class)
    @Documented
    public @interface Sex
    {
    
        String message() default "{customValidator.sex";
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    
        @Target({ FIELD, METHOD, ANNOTATION_TYPE })
        @Retention(RUNTIME)
        @Documented
        @interface List
        {
            Sex[] value();
        }
    }
    


    public class SexValidator implements ConstraintValidator<Sex, Character> {
    
        public void initialize(Sex sex)
        {
            // used only if your annotation has attributes
        }
    
        public boolean isValid(Character sex, ConstraintValidatorContext constraintContext)
        {
            // Bean Validation specification recommends to consider null values as
            // being valid. If null is not a valid value for an element, it should
            // be annotated with @NotNull explicitly.
            if (sex == null)
            {
                return true;
            }
            if (sex.equals('F') || sex.equals('M'))
                return true;
    
            else
            {
                return false;
            }
    
        }
    }
    


    @Column(name = "sex", columnDefinition = "char(1)")
    @NotNull
    @Sex
    private Character sex;