Javax.Validation - 允许 null 但如果值不是则验证

Its*_*has 8 java validation

我正在使用 javaxValidation.constraints并且我想验证输入但允许它为空,我的 POJO:

public class somePOJO{
    @NotNull
    @Size(min =2, max=50)
    @Pattern(regexp="^[A-Za-z \\s\\-]*$")
    private String country;

    @Size(min =2,max=50)
    @Pattern(regexp="^[A-Za-z \\s\\-]*$")
    private String state;
    //gettes, setters.....

}
Run Code Online (Sandbox Code Playgroud)

我想验证state,例如, @Pattern并且@size仅当它不是null

有没有办法使用自定义注释来做到这一点?

ygo*_*gor 6

正如您所期望的那样,这是开箱即用的,例如在 Spring Boot、2.1.0(以及 Quarkus FWIW)中。

这是 POJO 的完整版本(请注意,我提倡的是不可变类):

package sk.ygor.stackoverflow.q53207105;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public class SomePOJO {

    @NotNull
    @Size(min =2, max=50)
    @Pattern(regexp="^[A-Za-z \\s\\-]*$")
    private final String country;

    @Size(min =2,max=50)
    @Pattern(regexp="^[A-Za-z \\s\\-]*$")
    private final String state;

    public SomePOJO(String country, String state) {
        this.country = country;
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public String getState() {
        return state;
    }

}
Run Code Online (Sandbox Code Playgroud)

如果您关心空字符串,您可以通过向正则表达式添加尾随管道来接受它们(这意味着“此表达式或空字符串”),尽管这会破坏Size()要求:

@Pattern(regexp="^[A-Za-z \\s\\-]*$|")
Run Code Online (Sandbox Code Playgroud)

完整版控制器:

package sk.ygor.stackoverflow.q53207105;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
public class ExampleController {

    @RequestMapping(path = "/q53207105", method = RequestMethod.POST)
    public void test(@Valid @RequestBody SomePOJO somePOJO) {
        System.out.println("somePOJO.getCountry() = " + somePOJO.getCountry());
        System.out.println("somePOJO.getState() = " + somePOJO.getState());
    }

}
Run Code Online (Sandbox Code Playgroud)

使用以下命令调用 http://localhost:8080/q53207105:

{
    "country": "USA",
    "state": "California" 
}
Run Code Online (Sandbox Code Playgroud)

印刷:

somePOJO.getCountry() = USA
somePOJO.getState() = California
Run Code Online (Sandbox Code Playgroud)

使用以下命令调用 http://localhost:8080/q53207105:

{
    "country": "USA",
}
Run Code Online (Sandbox Code Playgroud)

印刷:

somePOJO.getCountry() = USA
somePOJO.getState() = null
Run Code Online (Sandbox Code Playgroud)

如果您告诉我您的 Spring Boot 版本,我可能会提供更多帮助。