1

I am validating java beans using spring-boot-starter-validation.

Validation on the controller is working fine,

I want to know whether can we validate the normal methods of a class using @Valid annotation? I have tried it but not working.

My working solution on the controller

@PostMapping("/testMessage")
    ResponseEntity<String> testMethod(@Valid @RequestBody InternalMsg internalMsg) {
        return ResponseEntity.ok("Valid Message");
    }

I want to move the validation to a class method so that when I hit the RestAPI, the validation errors are captured in a new method.

Let's say the method is validateMsg of class MsgValidator and I am calling this method inside controller code

@PostMapping("/testMessage")
ResponseEntity<String> testMethod(@RequestBody InternalMsg internalMsg) { // No @Valid here
        MsgValidator msgValidator = new MsgValidator();
        Boolean isValid = msgValidator.validateMsg(internalMsg);
        // some other processings
        return ResponseEntity.ok("Valid Message");
}

public class MsgValidator{
   public boolean validateMsg(@Valid InteropMsg interopMsg){
     return true;
   }
   
   @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Ack> handleValidationExceptions(MethodArgumentNotValidException ex) {
        StringBuilder errorMessages = new StringBuilder("");
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            errorMessages.append(error.getDefaultMessage()).append(";");
        });
        log.error("Validation errors : "+errorMessages.toString());
        return ResponseEntity.ok().body(ack);
    }
}

public class InternalMsg implements Serializable {
    @NotNull(message = "Msg Num is a required field")
    private String msgNumber;
    @NotNull(message = "Activity Name is a required field")
    private String activityName;
}

This is not working Please let me know how to achieve this

LearnToCode
  • 169
  • 1
  • 5
  • 19
  • I also found something related to this here - https://stackoverflow.com/questions/37827371/bean-validation-only-works-for-controller-methods-in-spring but it is @Validated – LearnToCode May 07 '21 at 11:56

1 Answers1

1

Below is an example of how you could use the ValidatorFactory to get a Validator to do the validation rather than using the @Valid annotation.

    InternalMsg internalMsg = new InternalMsg();

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<InternalMsg>> validate = validator.validate(internalMsg);

See here for more details -> https://www.baeldung.com/javax-validation

The below is just a snippet and not necessarily the recommended way of using the ValidationFactory

Garreth Golding
  • 985
  • 2
  • 11
  • 19