JSR-303 validation groups define a default group

前端 未结 2 1708
时光取名叫无心
时光取名叫无心 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: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 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 {}
    }
    

提交回复
热议问题