【问题标题】:Can we add parameters to Json validation annonations?我们可以在 Json 验证注解中添加参数吗?
【发布时间】:2022-02-03 09:34:28
【问题描述】:

我正在做如下的 json 字段验证:

    @Valid
    @NotEmpty(message="Id must not be empty")
    @Size(min=1, max=70, message="Id accepts max length of 70")
    private String Id;
    @Valid
    @NotEmpty(message="application must not be empty")
    @Size(min=1, max=8, message="application accepts max length of 8")
    private String application;

这工作正常 但是现在我有另一个要求,在验证第二个字段时,我还需要将 id 传递给消息,说明此应用程序消息是针对哪个 id 来的

示例:应用程序不能为 id = 123 的空 或者 应用程序接受 id = 456 的最大长度为 8

我不确定是否可以将模型中的其他属性传递给消息 如果您有任何线索,请发表评论

【问题讨论】:

  • 我尝试过类似@Size(min=4, max=4, message="application value should be of length 4 ${modelName.id}") 但得到“引用未知属性”错误

标签: java json validation


【解决方案1】:

据我所知,只能获取当前验证值以及注释方法中的值(最小值、最大值等)。如果有人真的知道方法,请随时纠正我。

要实现对另一个属性值的访问,您需要在类型级别上自定义验证注释。我假设保存数据的类称为MyModel。注释可能如下所示:

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyModelApplicationSizeValidator.class)
public @interface MyModelApplicationSize {

    String message() default "default message";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    int min() default 0;

    int max() default Integer.MAX_VALUE;
}

以及这个注解的实际验证器:

import com.example.random.model.MyModel;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class MyModelApplicationSizeValidator implements ConstraintValidator<MyModelApplicationSize, MyModel> {

    private int min;
    private int max;
    private String msgFormat;

    @Override
    public void initialize(MyModelApplicationSize constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
        this.msgFormat = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(MyModel model, ConstraintValidatorContext context) {
        String value = model.getApplication();
        if (value == null || value.isEmpty() || value.length() < this.min || value.length() > this.max) {
            context.disableDefaultConstraintViolation();
            String message = String.format(this.msgFormat, this.min, this.max, value, model.getId());
            context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
            return false;
        }
        return true;
    }
}

请记住,使用 String.format 构建错误消息并不是最好的方法,它有点脆弱,您实际上可能需要根据您的需要以另一种方式实现它。

还有MyModel,用新注解验证:

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;

@MyModelApplicationSize(message = "application accepts min length of %d and max length of %d for val - %s with id - %s", min = 2, max = 7)
public class MyModel {

    @NotEmpty(message="Id must not be empty")
    @Size(min=1, max=70, message="Id accepts max length of 70")
    private String id;

    @NotEmpty(message="application must not be empty")
    @Size(min=1, max=8, message="application accepts min length of {min} and max length of {max} for val - ${validatedValue}")
    private String application;

    //getters and setters
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多