Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 889
Poonkodi Sivapragasam Avatar asked Feb 05 '18 01:02

Poonkodi Sivapragasam


People also ask

What happens when @valid fails?

When you use the @Valid annotation for a method argument in the Controller , the validator is invoked automatically and it tries to validate the object, if the object is invalid, it throws MethodArgumentNotValidException .

Is @valid and @validated the same?

The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.

What does @valid mean in Spring boot?

The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen is between 1 and 10 inclusive because of those min and max annotations.

Where is @valid annotation is used to validate a form?

In controller class: The @Valid annotation applies validation rules on the provided object. The BindingResult interface contains the result of validation.

What is @valid annotation in Spring Boot?

@Valid and @Validated Annotations In Spring, we use JSR-303's @Valid annotation for method level validation. Moreover, we also use it to mark a member attribute for validation. However, this annotation doesn't support group validation.

What is Bean Validation in Spring Boot?

When the client passes JSON in the request body, Spring will automatically map this JSON to a Java object. Bean Validation defines constraints to the fields of a class by annotating them with certain annotations.

What is Hibernate Validator in Spring Boot?

Hibernate Validator implements all requirements from a validation API specification and Spring provides a validation starter for using Java Bean Validation with Hibernate Validator. There are built-in constraints, and you can also define your own custom constraints.

Can the @valid annotation be used in Java Bean Validation?

Name cannot be an empty string nor null and address cannot be null. Address class has street and city that cannot be empty nor null and postcode with size between 4 and 6 characters. @Valid annotation comes from Java Bean Validation API mentioned above, lets use it in our controller.


4 Answers

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.

like image 141
Deb Avatar answered Oct 21 '22 23:10

Deb


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>
like image 36
Thanny Avatar answered Oct 21 '22 22:10

Thanny


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)

like image 18
surya Avatar answered Oct 21 '22 23:10

surya


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

like image 15
firstpostcommenter Avatar answered Oct 21 '22 23:10

firstpostcommenter