Javax.Validation-允许为null,但是验证该值是否不是

时间:2018-11-08 11:46:38

标签: java validation

我正在使用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

是否可以使用custom annotations来做到这一点?

3 个答案:

答案 0 :(得分:1)

如您所料,此功能开箱即用。在最新的Spring Boot 2.1.0中。

您正在使用哪个版本的Spring Boot?

这是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;
    }

}

控制器的完整版本:

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引导版本,我可能会提供更多帮助。

答案 1 :(得分:0)

InitBinder 中设置了 StringTrimmerEditor 时,您的POJP将按预期工作。

您可以拥有一个应用程序范围的InitBinder,在您的项目中有一个类似于下面的类。

@ControllerAdvice
public class CustomControllerAdvice {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
}

答案 2 :(得分:-1)

您可以在正则表达式中使用替代构造来分隔多个模式。只需使用管道“ |”分隔模式即根据您对现有regex的要求,将regex添加为空/空字符串。下面的示例:

char[]

可能不准确,但希望您能理解。

相关问题