Java8 Bean Validation for Enum type using Hibernate

1.1k Views Asked by At

Here's my situation,

I have a class with Enum type fields. I want to execute annotated validation for enum types, similar to annotations for strings, example: @Size, @NotNull etc.

Problem is, json deserializer fails on enum type before validation occurs.

public class myClass {
    @JsonProperty
    //@SomeCustomValidator -- ??
    private EnumType enumValue;
}

public enum EnumType {
    A,
    B,
    C
}

Few things:

  1. I do not want to change the data type to String.
  2. Tried steps in following threads, didn't fix my problem.

    Tried this link, but get an error in deserialization before validation hits

    Tried this link, but it works only when data Type is String

1

There are 1 best solutions below

2
Bogdan Lukiyanchuk On

Validation works after the type of the argument is resolved. So I don't see a way how to use String validating annotations on enums. As workaround you can use @JsonCreator and do some validation before object creation.

public enum EnumType {
    A,
    B,
    C;

    @JsonCreator
    public static EnumType from(String s) {
        // add your logic here, for example
        /*
        if (Stream.of(values()).map(Enum::name).noneMatch(name -> name.equals(s))) {
            throw new MyServiceException("Bad value " + s);
        }
        */
        return valueOf(s);
    }
}