JSR-303 validation groups define a default group

前端 未结 2 1704
时光取名叫无心
时光取名叫无心 2020-12-31 00:50

I have a bean that has a lot of fields annotated with JSR-303 validation annotations. There is a new requirement now that one of the fields is mandatory, but only in certain

相关标签:
2条回答
  • 2020-12-31 01:24

    There is a Default group in javax.validation.groups.Default, which represents the default Bean Validation group. Unless a list of groups is explicitly defined:

    • constraints belong to the Default group
    • validation applies to the Default group

    You could extends this group:

    public interface ValidatedOnCreationOnly extends Default {}
    
    0 讨论(0)
  • 2020-12-31 01:25

    just wanted to add more:

    if you're using spring framework you can use org.springframework.validation.Validator

    @Autowired
    private Validator validator;
    

    and to perform validation manually:

    validator.validate(myObject, ValidationErrorsToException.getInstance());
    

    and in controller:

    @RequestMapping(method = RequestMethod.POST)
    public Callable<ResultObject> post(@RequestBody @Validated(MyObject.CustomGroup.class) MyObject request) {
        // logic
    }
    

    although in this way extending from javax.validation.groups.Default won't work so you have to include Default.class in groups:

    class MyObject {
    
        @NotNull(groups = {Default.class, CustomGroup.class})
        private String id;
    
        public interface CustomGroup extends Default {}
    }
    
    0 讨论(0)
提交回复
热议问题