[英]Javax.Validation - allow null but validate if the value is not
我正在使用 javax Validation.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.....
}
我想驗證state
,例如@Pattern
和@size
僅當它不是null
。
有沒有辦法使用自定義注釋來做到這一點?
這正如您所期望的那樣開箱即用,例如在 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;
}
}
如果您關心空字符串,您可以通過向正則表達式添加尾隨管道來接受它們(這意味着“此表達式或空字符串”),盡管這會破壞Size()
要求:
@Pattern(regexp="^[A-Za-z \\s\\-]*$|")
完整版控制器:
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());
}
}
使用以下命令調用 http://localhost:8080/q53207105:
{
"country": "USA",
"state": "California"
}
印刷:
somePOJO.getCountry() = USA
somePOJO.getState() = California
使用以下命令調用 http://localhost:8080/q53207105:
{
"country": "USA",
}
印刷:
somePOJO.getCountry() = USA
somePOJO.getState() = null
如果您告訴我您的 Spring Boot 版本,我可能會提供更多幫助。
您可以在正則表達式中使用交替構造來分隔多個模式。 只需使用管道'|'分隔模式即根據您對現有正則表達式的要求為空/空字符串附加正則表達式。 示例如下:
^(?:[A-Za-z \\s\\-]*|)$
可能不准確,但希望你有這個想法。
當在InitBinder 中設置了StringTrimmerEditor時,您的 POJP 將按預期工作。
您可以擁有一個應用程序范圍的 InitBinder,在您的項目中有一個如下所示的類。
@ControllerAdvice
public class CustomControllerAdvice {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.