简体   繁体   English

Bean验证-验证可选字段

[英]Bean validation - validate optional fields

Given a class that represents payload submitted from a form, I want to apply bean validation to a field that may or may not be present, for example: 给定一个表示从表单提交的有效负载的类,我想将bean验证应用于可能存在或可能不存在的字段,例如:

class FormData {
    @Pattern(...)
    @Size(...)
    @Whatever(...)
    private String optionalField;

    ...
} 

If optionalField is not sent in the payload, I don't want to apply any of the validators above, but if it is sent, I want to apply all of them. 如果没有在有效负载中发送optionalField ,则我不想应用上面的任何验证器,但是如果发送了验证器,则我想应用所有验证器。 How can it be done? 如何做呢?

Thanks. 谢谢。

So usually all of these constraints consider null value as valid. 因此通常所有这些约束都将null值视为有效。 If your optional filed is null when it's not part of the payload all should work just fine as it is. 如果您的可选字段不为有效负载的一部分时为null ,则所有字段都应该可以正常工作。

And for any mandatory fields you can put @NotNull on them. 对于任何必填字段,您可以在其上加上@NotNull

EDIT here's an example: 编辑这是一个例子:

class FormData {
    @Pattern(regexp = "\\d+")
    @Size(min = 3, max = 3)
    private final String optionalField;

    @Pattern(regexp = "[a-z]+")
    @Size(min = 3, max = 3)
    @NotNull
    private final String mandatoryField;
}

@Test
public void test() {
    Validator validator = getValidator();

    // optonal field is null so no violations will rise on it
    FormData data = new FormData( null, "abc" );
    Set<ConstraintViolation<FormData>> violations = validator.validate( data );
    assertThat( violations ).isEmpty();

    // optional field is present but it should fail the pattern validation:
    data = new FormData( "aaa", "abc" );
    violations = validator.validate( data );
    assertThat( violations ).containsOnlyViolations(
            violationOf( Pattern.class ).withProperty( "optionalField" )
    );
}

You can see that in the first case you don't get any violations as the optional field is null . 您会看到在第一种情况下,您不会收到任何违规信息,因为可选字段为null but in the second exmaple you receive a violation of pattern constraint as aaa is not a string of digits. 但在第二个示例中,由于aaa不是数字字符串,您会收到违反模式约束的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM