1

I am trying to add string input to spring boot application. The content type is json and I am trying to add validation to it.

@RestController
@RequestMapping(value = "/entries")
public class SampleController {

    @RequestMapping(method = RequestMethod.DELETE)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    public void delete(@RequestBody @NotBlank(message = "{field.required}") String username) throws Exception {
        //some logic
    }

}

For some reasons, @Notblank annotation does not work.

Is it right way to do it.

Patan
  • 17,073
  • 36
  • 124
  • 198

2 Answers2

2

one way to go would be creating a model/dto class and defining your @NotBlank on a String in this class. then just change your controller-code like this:

    @RequestMapping(method = RequestMethod.DELETE)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    public void delete(@RequestBody @Valid MyClass myClass) throws Exception {
        ...
    }

For more insights, look here

Dominik
  • 2,801
  • 2
  • 33
  • 45
1

You can't use those validations on method parameters. You need to bind your parameter onto an object if you want validation. Then, you just have to add @Valid annotation. See this example.

Community
  • 1
  • 1
nnunes10
  • 550
  • 4
  • 14