How to set check order for JSR303 bean validation

后端 未结 3 1857
情书的邮戳
情书的邮戳 2021-01-01 03:57

I use the JSR303 Bean Validation to check the form input.

@NotBlank
@Size(min = 4, max = 30)
private String name;

@NotBlank
@Size(max = 100)
@Email
private          


        
相关标签:
3条回答
  • 2021-01-01 04:04

    Have you considered to define two sequences. One for name and one for mail?

    @GroupSequence({NameFirst.class, NameSecond.class})
    interface AllName {
    }
    
    @GroupSequence({MailFirst.class, MailSecond.class, MailThird.class})
    interface AllMail {
    }
    

    In this case you would call the validator like this:

    validator.validate(myObject, AllName.class, AllMail.class)
    
    0 讨论(0)
  • 2021-01-01 04:14

    Yes Bean Validation supports this feature. It is called validation groups and group sequences. Groups are simple marker interfaces, for example you could create the two interfaces First and Second and change your code to something like this:

    @NotBlank(groups = First.class)
    @Size(min = 4, max = 30, groups = Second.class)
    private String name;
    

    Then you can define a group sequence:

    @GroupSequence({ First.class, Second.class})
    interface All {
    }
    

    Get hold of the Validator and call validator.validate(myObject, All.class)

    It's all in the documentation.

    0 讨论(0)
  • 2021-01-01 04:22

    The order of validation related annotations / constraints cannot be specified at time of writing this answer. I've submitted order related issue to Hibernate Validator team a time ago, the issue was was accepted and probably will be solved in a next Bean Validation specification release - see more details here: http://beanvalidation.org/proposals/BVAL-248/ Btw, in simple cases you can avoid "order conflict" by using "non conflicting" combinations of annotations, e.g. NotNull and Size - Size will evaluate to true for null value.

    0 讨论(0)
提交回复
热议问题