Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.validation: Constraint to validate a string length in bytes

I'm using javax.validation to validate some bean fields' values.

This is what I use normally:

public class Market {

    @NotNull
    @Size(max=4)
    private String marketCode;

    @Digits(integer=4, fraction=0)
    private Integer stalls;

    // getters/setters
}

This will make sure that every Market instance has a market code with a maximum length of 4 characters and a number of stall with a maximum of 4 integer digits and 0 decimal digits.

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

In the DB I have table Markets defined like this:

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

As you can see, I have MARKET_CODE which can be at most 4 bytes long. The @Size annotation will check if the string is at most 4 characters long, which is wrong.

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

like image 211
BackSlash Avatar asked Oct 13 '14 09:10

BackSlash


1 Answers

Check the Hibernate Validator documentation on Creating custom constraints.

Your validator will need to encode the String into a byte[], using some default or specified Charset. I imagine you might well use UTF-8.

Maybe something like this, which uses a hard coded UTF-8 encoding and assumes a suitable annotation, as outlined in the Hibernate documentation linked.

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;
    }
}
like image 179
ptomli Avatar answered Sep 19 '22 23:09

ptomli