1

I have following field with JSR-303 validation:

@Size(min = 6, max = 6, message = "Field needs to be 6 characters")
private String field;

Requirement for the field is to be 6 characters or null.

(I then use valdr-bean-validation (https://github.com/netceteragroup/valdr-bean-validation) to extract it to valdr format and use in AngularJS.)

Question: How can I met requirements, using JSR-303, so that the field can be null or 6 characters? At the moment my @Size rule expects at least 6 characters.

I don't want to use custom validator, because of compatibility with valdr. Is a regex good option? Thanks

FazoM
  • 4,777
  • 6
  • 43
  • 61

2 Answers2

3

I fixed it using @Pattern annotation with simple RegEx:

@Pattern(regexp = "^.{6,6}$|^$", message = "Field must be 6 digits or empty")
private String field;
FazoM
  • 4,777
  • 6
  • 43
  • 61
2

Yea, you should use @Pattern annotation on this field (or create your own annotation with both Size, Pattern and any other rules combination)

Cootri
  • 3,806
  • 20
  • 30