Home > Net >  DTO validation in Spring Boot not working
DTO validation in Spring Boot not working

Time:03-03

I have a controller with POST method:

        @RestController
        @RequestMapping(value = "/creditDetails", produces = MediaType.APPLICATION_JSON_VALUE)
        @RequiredArgsConstructor
        @Validated
        public class CreditDetailsController {
       
            @ResponseStatus(HttpStatus.CREATED)
            @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
            public CreditDetailsResponse createCreditDetails(@RequestBody @Valid CreditDetailsRequestWithoutId request) {
                return CreditDetailsResponse.convertToResponse(creditDetailsService.createCreditDetails(request));
            }
    }

And DTO:

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class CreditDetailsRequestWithoutId {
    @DecimalMax("10_000_000")
    private BigDecimal creditLimit;
    @DecimalMin("0")
    @DecimalMax("20")
    private BigDecimal creditPercent;
    private UUID bankId;
}

When I pass the CreditDetailsWithoutId instance with 111 percent I don't get any errors. Why my validation didn't work? If it matter i use

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <version>2.6.3</version>
        </dependency>

no problem

CodePudding user response:

Try to pass a decimal value to @DecimalMin, @DecimalMax,:

@DecimalMax: The value of the field or property must be a decimal value lower than or equal to the number in the value element. reference

@DecimalMin("0.0")
@DecimalMax("20.0")
private BigDecimal creditPercent;

Later edit: Removing @Data and adding basic getters & setters fixed the problem on my side, hope it works.

// @Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class CreditDetailsRequestWithoutId {

    @DecimalMax("20.0")
    private BigDecimal creditPercent;

    public BigDecimal getCreditPercent(){
        return creditPercent;
    }

    public void setCreditPercent(BigDecimal creditPercent){
        this.creditPercent = creditPercent;
    }
}

CodePudding user response:

You must add EexceptionHandler in your controller class:

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;


@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getAllErrors().forEach((error) -> {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    return errors;
}
  • Related