5

I have a view model in my spring mvc application and I need to enable or disable specific validation on some fields. For example, suppose I have a 2 view forms that sends data to different controller methods, but both methods use same view model class, something like this:

@RequestMapping(value = "/method1", method = RequestMethod.POST)
@ResponseBody
public ViewModel method1(@RequestBody @Valid ViewModel viewModel){
      ...
}

@RequestMapping(value = "/method2", method = RequestMethod.POST)
@ResponseBody
public ViewModel method2(@RequestBody @Valid ViewModel viewModel){
    ...
}

And this is part of my view model:

private Integer test;

I need to use @NotNull annotation on test field, but just in method2 in controller. In fact, I don't need this validation in method1. Is there any way for doing this?

hamed
  • 7,939
  • 15
  • 60
  • 114
  • Possible duplicate of [Validate partial Modal using Spring @Valid annotation](https://stackoverflow.com/questions/26804468/validate-partial-modal-using-spring-valid-annotation) – Arnaud Nov 07 '17 at 10:02
  • Duplicate of https://stackoverflow.com/questions/35704351/spring-rest-controller-how-to-selectively-switch-off-validation – Serban Gorcea Nov 07 '22 at 09:14

2 Answers2

-1

I think your approach should be to write a super class like

class ViewModel {
   @NotNull
   private Integer test;

   public Integer getTest() {
   }
}

class ViewModelSuper extends ViewModel {
   private Integer test;

   @Override
   public Integer getTest() {
   }
}


the you'll have 

@RequestMapping(value = "/method1", method = RequestMethod.POST)
@ResponseBody
public ViewModel method1(@RequestBody @Valid ViewModelSuper viewModel){
  ...
}

@RequestMapping(value = "/method2", method = RequestMethod.POST)
@ResponseBody
public ViewModel method2(@RequestBody @Valid ViewModel viewModel){
...
}

Since you only need validation for method2, the super class is used for method1

-2

Remove @valid in method1. It will not validate.