Javax.validation: Limit for checking string length in bytes

I use javax.validation to check some values โ€‹โ€‹of bean fields.

This is what I usually use:

 public class Market { @NotNull @Size(max=4) private String marketCode; @Digits(integer=4, fraction=0) private Integer stalls; // getters/setters } 

This ensures that each Market instance has a market code with a maximum of 4 characters and a number of stalls with a maximum of four integers and 0 decimal digits.

Now I use this bean to load / store data from / to DB.

In the DB, I have a Markets table defined as follows:

 CREATE TABLE MARKETS ( MARKET_CODE VARCHAR2(4 BYTE) NOT NULL, STALLS NUMBER(4,0) ) 

As you can see, I have a MARKET_CODE whose length does not exceed 4 bytes. @Size will check to see if the string contains a maximum of 4 characters, which is not true.

So the question is: is there an annotation like @Size that will check string bytes instead of characters?

+8
java string validation byte constraints
source share
1 answer

Check out the Hibernate Validator documentation for creating custom restrictions .

Your validator will need to encode String in byte[] using some standard or specified Charset . I suppose you could very well use UTF-8.

Maybe something like this that uses hard-coded UTF-8 encoding and suggests suitable annotation, as outlined in the Hibernate documentation.

 public class MaxByteLengthValidator implements ConstraintValidator<MaxByteLength, String> { private int max; public void initialize(MaxByteLength constraintAnnotation) { this.max = constraintAnnotation.value(); } public boolean isValid(String object, ConstraintValidatorContext constraintContext) { return object == null || object.getBytes(Charsets.UTF_8).length <= this.max; } } 
+7
source share

All Articles