Suule
Suule

Reputation: 2478

@RequestBody as a String is not being validated

I do have simple controller which accept String as RequestBody

  @RequestMapping(value = "/test", method = RequestMethod.POST)
  public ResponseEntity doSmth(@RequestBody @ValidTest String val) {

    //do something
    return ResponseEntity
            .status(HttpStatus.OK)
            .body("saved");
  }

But for some reason val param not being validated with TestConstraintValidator.class

@Documented
@Constraint(validatedBy = TestConstraintValidator.class)
@Target({PARAMETER})
@Retention(RUNTIME)
public @interface ValidTest{
    String message() default "Invalid";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Is there even option to validate this? Or do I need to wrap this String withing custom class. And validate it there?

public class TestConstraintValidator implements ConstraintValidator<ValidTest, String> {
    @Override
    public void initialize(ValidTest constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(String val, ConstraintValidatorContext constraintValidatorContext) {
       
        return false;
    }
}

Upvotes: 0

Views: 274

Answers (1)

Toni
Toni

Reputation: 5165

Make sure the controller class is marked as @Validated.

Upvotes: 1

Related Questions