javax.validation:约束以字节为单位验证字符串长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26337002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:15:59  来源:igfitidea点击:

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

javastringvalidationbyteconstraints

提问by BackSlash

I'm using javax.validationto validate some bean fields' values.

javax.validation用来验证一些 bean 字段的值。

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 Marketinstance has a market code with a maximum length of 4characters and a number of stall with a maximum of 4 integer digits and 0 decimal digits.

这将确保每个Market实例都有一个最大4字符长度的市场代码和一个最多4 个整数位和 0 个小数位的档位。

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

现在,我使用这个 bean 从/向 DB 加载/存储数据。

In the DB I have table Marketsdefined like this:

在数据库中,我Markets定义了如下表:

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

As you can see, I have MARKET_CODEwhich can be at most 4 byteslong. The @Sizeannotation will check if the string is at most 4 characterslong, which is wrong.

如您所见,我MARKET_CODE最多可以有 4个字节长。该@Size注释将检查字符串最多为4个字符长,这是错误的。

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

所以,问题是:是否有这样的注释@Size会检查字符串字节而不是字符?

采纳答案by ptomli

Check the Hibernate Validator documentation on Creating custom constraints.

查看有关创建自定义约束Hibernate Validator 文档

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

您的验证器将需要使用一些默认或指定的将 编码String为。我想你很可能会使用 UTF-8。byte[]Charset

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

也许像这样,它使用硬编码的 UTF-8 编码并假定合适的注释,如链接的 Hibernate 文档中所述。

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;
    }
}