是否可以使用单个(最好是基于 Spring 的)自定义注释返回多个/变量错误消息?

发布于 2024-11-12 12:23:38 字数 2046 浏览 2 评论 0原文

我目前正在使用 Spring 进行所有验证,但想要构建一个自定义注释来将单个字段上的多个条件组合在一起,有条件地并使用变量值验证其中一些条件,即类似以下内容:

public @interface CustomAnno
{
    @NotNull
    @Length(min = 1, max = 10, applyIf = "condition == 1")
    @Length(min = 11, max = 20, applyIf = "condition == 2")
    String val();
    int condition();
}

我知道这在语法上不正确,但希望这能明白我想要做的事情。

我的问题是,像上面这样的事情是否可能,并且单个 CustomAnno 注释是否能够为所有失败的条件返回错误,而不是仅仅为 CustomAnno 返回单个失败?

编辑:我可能不一定使用 Spring 注释来驱动值的验证。理想情况下,我会在处理 CustomAnno 的 ConstraintValidator 中使用任意验证逻辑,如果我的理解正确,则只会针对 isValid 调用中的一个可能错误返回 true 或 false。我实际上正在寻找的是实现与上述相同功能的东西,但具有来自验证器的注释或自定义逻辑,即:

public class CustomAnnoValidator implements ConstraintValidator<CustomAnno,String>
{
    @NotNull
    String val;
    int cond;
    String regex;
    List<String> errors;

    private void err(String msg)
    {
        errors.add(msg);
    }

    public void initialize(CustomAnno anno)
    {
        this.val = anno.val();
        this.cond = anno.condition();
        this.errors = new ArrayList<String>();
        this.regex = "[A-Za-z]+[A-Za-z0-9]+";
    }

    public boolean isValid(String object, ConstraintValidatorContext constraintContext)
    {
        if (cond == 1)
        {
            if (object.length() > 10)
                err("Length must be less than 10");
            else if (object.length() < 1)
                err("Length must be greater than 1");
        }
        else if (cond == 2)
        {
            if (object.length() > 21)
                err("Length must be less than 21");
            else if (object.length() < 10)
                err("Length must be greater than 10");
        }

        if (!val.matches(regex))
            err("Must start with an alpha character and consist of only alphanumeric characters.");

        // some method to add the error messages, ie => constraintContext.addErrors(errors);

        return errors.size() > 0;
    }
}

我想理论上我可以为我缺少的任何单个条件创建自定义注释,可能会让这个问题变得很简单,但想知道验证器是否可以处理多种条件

I'm currently using Spring for all of my validation, but wanted to build a custom annotation to group together a number of conditions on a single field, validating some of them conditionally and with variable values, ie something along the lines of:

public @interface CustomAnno
{
    @NotNull
    @Length(min = 1, max = 10, applyIf = "condition == 1")
    @Length(min = 11, max = 20, applyIf = "condition == 2")
    String val();
    int condition();
}

I know that isn't syntactically correct, but hopefully that gets the point across of what I'm trying to do.

My question is, is something like the above even possible, and would that single CustomAnno annotation be able to return errors for all of the conditions that fail, instead of just returning a single failure for CustomAnno?

Edit: I may not necessarily be using Spring annotations to drive the validation for a value. Ideally I would be using arbitrary validation logic in the ConstraintValidator that handles CustomAnno, which if my understanding is correct will only return true or false for one possible error in the isValid call. What I'm actually looking for is something that achieves the same functionality as the above, but with either annotations or custom logic from the validator, ie:

public class CustomAnnoValidator implements ConstraintValidator<CustomAnno,String>
{
    @NotNull
    String val;
    int cond;
    String regex;
    List<String> errors;

    private void err(String msg)
    {
        errors.add(msg);
    }

    public void initialize(CustomAnno anno)
    {
        this.val = anno.val();
        this.cond = anno.condition();
        this.errors = new ArrayList<String>();
        this.regex = "[A-Za-z]+[A-Za-z0-9]+";
    }

    public boolean isValid(String object, ConstraintValidatorContext constraintContext)
    {
        if (cond == 1)
        {
            if (object.length() > 10)
                err("Length must be less than 10");
            else if (object.length() < 1)
                err("Length must be greater than 1");
        }
        else if (cond == 2)
        {
            if (object.length() > 21)
                err("Length must be less than 21");
            else if (object.length() < 10)
                err("Length must be greater than 10");
        }

        if (!val.matches(regex))
            err("Must start with an alpha character and consist of only alphanumeric characters.");

        // some method to add the error messages, ie => constraintContext.addErrors(errors);

        return errors.size() > 0;
    }
}

I guess theoretically I could create custom annotations for any of the single conditions that I am missing, potentially making this question a wash, but was wondering if it were possible for the validator to handle multiple conditions

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

明媚如初 2024-11-19 12:23:38

不知道你说的Spring注解是什么意思? Spring MVC 被设计为与 JSR-303 一起使用,这就是那些 javax.validation jar 所描述的。

Spring MVC 验证应该为每个失败的验证返回错误消息,即使这些验证被分组在单个自定义注释中。

http://static.springsource.org /spring/docs/3.0.x/spring-framework-reference/html/validation.html

I'm not sure what you mean by Spring annotations? Spring MVC is designed to work with JSR-303, which is what those javax.validation jars describe.

Spring MVC validation should return error messages for every failed validation, even if those validations are grouped together in a single custom annotation.

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/validation.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文