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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With