简体   繁体   中英

Spring boot validation annotations @Valid and @NotBlank not working

Given below is my main controller from which I am calling the getPDFDetails method.

@RequestMapping(value=PATH_PRINT_CONTRACTS, method=RequestMethod.POST)
    public ResponseEntity<?> printContracts(@RequestBody final UpdatePrintContracts updatePrintContracts) throws Exception {
    
        System.out.println("contracts value is "+ updatePrintContracts);
        
        Integer cancellationReasons = service.getPDFDetails(updatePrintContracts);
        
        System.out.println("success!");
        
        return ResponseEntity.ok(cancellationReasons);
    }   

Below is the UpdatePrintContracts class where I have defined all the variables with validation annotations and corresponding getter/setter methods.

public class UpdatePrintContracts {
    
    @Valid
    @NotBlank
    @Pattern(regexp = "\\p{Alnum}{1,30}")
    String isReprint;
    
    @Valid
    @NotBlank
    Integer dealerId;
    
    @Valid
    @NotBlank
    @Pattern(regexp = "\\p{Alnum}{1,30}")
    String includeSignatureCoordinates;
    
    @Valid
    @NotBlank
    java.util.List<Integer> contractNumbers;

    public String getIsReprint() {
        return isReprint;
    }

    public void setIsReprint(String isReprint) {
        this.isReprint = isReprint;
    }

    public Integer getDealerId() {
        return dealerId;
    }

    public void setDealerId(Integer dealerId) {
        this.dealerId = dealerId;
    }

    public String getIncludeSignatureCoordinates() {
        return includeSignatureCoordinates;
    }

    public void setIncludeSignatureCoordinates(String includeSignatureCoordinates) {
        this.includeSignatureCoordinates = includeSignatureCoordinates;
    }

    public java.util.List<Integer> getContractNumbers() {
        return contractNumbers;
    }

    public void setContractNumbers(java.util.List<Integer> contractNumbers) {
        this.contractNumbers = contractNumbers;
    }
    
}

I am trying to run the application as a Spring Boot app by right clicking on the project (Run As) and passing blank values for variables isReprint and includeSignatureCoordinates through Soap UI. However the validation doesn't seem to work and is not throwing any validation error in Soap UI. What am I missing? Any help is appreciated!

If you are facing this problem in latest version of spring boot (2.3.0) make sure to add the following dependency:

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

Observation: In earlier version of Spring Boot (1.4.7), javax.validation used to work out of the box. But, after upgrading to latest version, annotations broke. Adding the following dependency alone doesn't work:

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
</dependency>

Because this provides JSR Specification but not the implementation. You can also use hibernate-validator instead of spring-boot-starter-validation .

For Anyone who is getting this issue with 2.0.1.Final :

In all SpringBoot versions above 2.2, Validations starter is not a part of web starter anymore

Check Notes here

So, all you have to do is add this dependency in your build.gradle/pom file

GRADLE:

implementation 'org.springframework.boot:spring-boot-starter-validation'

MAVEN

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

First you dont need to have @Valid annotation for those class variables in UpdatePrintContracts . You can delete them.

To trigger validation of a @Controller input, simply annotate the input argument as @Valid or @Validated:

@RequestMapping(value=PATH_PRINT_CONTRACTS, method=RequestMethod.POST)
public ResponseEntity<?> printContracts(@Valid @RequestBody  final UpdatePrintContracts updatePrintContracts) throws Exception {

Refer here for full understanding of validating models in spring boot.

And If you want to check that a string contains only specific characters, you must add anchors (^ for beginning of the string, $ for end of the string) to be sure that your pattern matches all the string.Curly brackets are only to write a quantity,

@Pattern(regexp = "^[\\p{Alnum}]{1,32}$")

Lastly i assume you have following jars in your classpath,

.validation-api.jar (contains the abstract API and the annotation scanner)

.hibernate-validator.jar (contains the concrete implementation)

I was using This dependency of validation in spring boot and didn't work ,

<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>

I replaced it with spring-boot-starter-validation and it worked .

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot- 
starter-validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.4.0</version>

My problem solved by this. When we use classes inside classes that also need validations so @Valid needs to be annotated to all in that case. Link for more details

this is for anyone here who still has the same issue after following the steps mentioned above. I had to restart my IDE (IntelliJ) for the changes to take effect.

I faced the same error.

I had to use the below 2 dependencies alone:

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

And use @Validated annotation(import org.springframework.validation.annotation.Validated) on rest controller level and @Valid annotation at method argument level(import javax.validation.Valid)

If there are any other extra dependencies like javax.validation.validation-api , org.hibernate.hibernate-validator , etc then the validations stopped working for me. So make sure that you remove these dependencies from pom.xml

You have to add this dependency in pom.xml

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

Step-1: Add these two dependency in the pom.xml file

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>

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

Step-2: Create a Custom Exception class like this

package com.bjit.salon.auth.service.exceptions;


import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
public class AnynameApplicationException {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<List<String>> processUnmergeException(final 
MethodArgumentNotValidException ex) {

        List<String> list = ex.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());

        return new ResponseEntity<>(list, HttpStatus.BAD_REQUEST);
    }
}

Step-3: Add @Valid annotation to the method arguments like this way

public ResponseEntity<?> registerAccount(@Valid @RequestBody UserRegisterDto 
      registerDto) {
       
    // rest of the codes
}

Make sure to use @Valid annotation before @RequestBody

For newer versions of spring boot ensure all validation annotation are picked from jakarta.validation.* package and not javax.validation.* . As the annotations are named same in both.

You can use @NotEmpty will check for both blank and null values. Add @Valid to your RestContoller class methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM