4

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

  • For starters start by removing `@Validated` from the controller class. Secondly I wonder if `spring-boot-starter-validation` is the only validator you have or that you proactively added `hibernate-validator` version 7 or higher (or specified a version in the version management). – M. Deinum Mar 03 '22 at 07:19
  • @M.Deinum starter is the only validator I have – Smetana Po Aktsii Mar 03 '22 at 16:47

3 Answers3

2

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("1E+7")
    private BigDecimal creditLimit;

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

    public BigDecimal getCreditPercent(){
        return creditPercent;
    }

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

    public BigDecimal getCreditLimit(){
        return creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit){
        this.creditLimit = creditLimit;
    }
}

happy songs
  • 835
  • 8
  • 21
1

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;
}
  • 1
    Adding an exception handler wont change a thing. – M. Deinum Mar 03 '22 at 07:20
  • Please check this [link](https://github.com/mjimani/springBootValidation) ,This code works for me. – Mohammad Javad Mar 03 '22 at 08:23
  • Again it won't make a difference and in fact it interferes with the default handling that SPring Boot provides. Currently there is no exception being thrown due to no validation being done. No error makes the exception handler pretty useless. Which is also the reason adding it won't make any difference. – M. Deinum Mar 03 '22 at 08:38
  • @MohammadJavad i changed @DecimalMax("20.00") to @DecimalMax(value = "20") but nothing changed – Smetana Po Aktsii Mar 03 '22 at 16:58
  • @SmetanaPoAktsii please download this project and run it in your local. [PLEASE DOWNLOAD](https://github.com/mjimani/springBootValidation) – Mohammad Javad Mar 05 '22 at 04:42
1

I've just called maven clean install and validation started

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 04 '22 at 06:00