1

I've a request with an Enum inside and I can validate it with @NotNull but if I try to insert @NotEmpty too it does not work. This is a sample of what I would like to achieve.

@NotNull
@NotEmpty
private MyEnum myEnum;

How can I make it works?

5
  • 1
    @NotNull is sufficient, you don't need @NotEmply, because any other value which is not part of your enum will not work, let me know if I am missing something Commented Nov 5, 2019 at 9:39
  • Yep, but it is not possible to create a custom message when the field is empty. How can I do? Commented Nov 5, 2019 at 9:45
  • it's an enum. It will either be null or enum value. Commented Nov 5, 2019 at 9:54
  • Not at all. If I make a request in json format anche put inside "myEnum": "" and I don't want this without a custom response message Commented Nov 5, 2019 at 9:57
  • 3
    What you send in the request isn't what is one-on-one mapped. An empty string will result in an error when converting to an enum and it won't even reach the validation state, unless it is transformed to null then the @NotNull will kick in. Commented Nov 5, 2019 at 10:00

2 Answers 2

1

The javax @NotEmpty can only be applied CharSequence, Collection, Map or Array values (see documentation)

Empty and enum does not really make sense, except if you have an enum with an empty value, for example:

public enum MyEnum {
    NOT_EMPTY("notEmpty"), EMPTY("");
}

So the question would be how to validate for specific enum values or subsets.

In that case you would have to define your own validation annotation.

Sign up to request clarification or add additional context in comments.

2 Comments

So there is not a way to handle this by ResponseEntityExceptionHandler?
It is not really clear what case you are trying to do. As M. Deinum mentioned in your comments if "" is passed as the enum an error will be thrown before validation because the JSON can not be parsed as there is no enum for "" (Same as if someone sent "NO_ENUM_FOR_THIS" and there is no Enum named like that). In my case I get a org.springframework.http.converter.HttpMessageNotReadableException, similar as if I expected a numeric value and someone submitted a String.
0

Like Shailesh Chandra has mentioned in the comment we don't need to mention @NotEmpty or @NotBlank annotations for ENUM types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.