1

I've a RESTeasy application using Jackson and Bean Validation. A POJO might loo like this:

public class Foo {

    @Size(min = 2)
    private String bar;

}

Bar is validated if the client sends the bar property. And es expected: If the client does not send the property nothing will be validated.

If the client sends an empty String I'll get a constraint violation. This may be correct but it's hard to control what the value of an empty input field really is. For instance in my angular application the field will not be present if the user did not enter anything. Once he enters and deletes something I'll have an empty String.

I thought I could configure Jacksons behavior via DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT but as answered here this is only working for POJOs not for Strings. The only ways I see is not using @Size or writing an own deserializer for Strings. Both doesn't seem to be good solutions. Anyone other ideas?

Community
  • 1
  • 1
lefloh
  • 10,653
  • 3
  • 28
  • 50

1 Answers1

1

If you want to accept the empty string, you could use the @Pattern constraint matching also the empty string: @Pattern(regexp = "^$|(.){2}") or @Pattern(regexp = "^$|...

The alternative is to write your own custom constraint.

Hardy
  • 18,659
  • 3
  • 49
  • 65