简体   繁体   中英

Why is Java saying I can't use @NotBlank with a string

I have the following code

import javax.validation.constraints.NotBlank;
...
@NotBlank(message="Not Blank")
private String thing;

When I try to run I get

No validator could be found for constraint 'javax.validation.constraints.NotBlank' validating type 'java.lang.String'

How do I use NotBlank annotation with a string?

Java 8

The javax.validation.constraints.NotBlank annotation you are applying is part of Bean Validation API v2 .

The most probable case is:

  • You have bean validation API v2 as dependency on your project
  • The implementing framework/library supports only v1.0/v1.1 API.

Please check on this post for information about existing implementations: Is there JSR-303 implementation available?

I recommend you checking for bean validation API v2 on your classpath (it also can be called JSR-380). The only implementation of this API I know about is Hibernate Validator v6.0. Make sure that v2 implementation is not hidden by some v1.x implementation being on classpath.

I have encountered this problem and solved it. Because the validation version conflicts, In my project, the error was introduced twice validate。check the jar package, and then remove, then successful。

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.1.0.Final</version>
</dependency>
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

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