java 如何在非强制字段 JSR 303 上使用 @Pattern

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5998978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:54:50  来源:igfitidea点击:

How to use @Pattern on non-mandatory fields JSR 303

javavalidationspring-mvcbean-validation

提问by Erhan Bagdemir

How can i use @Patternconstraint on non-mandatory form fields ?

如何@Pattern对非强制性表单字段使用约束?

@Pattern(regexp="...")
private String something;

as soon as i submit my form, i get validation error as expected but the user may leave the field empty, since this is not a mandatory field.

一旦我提交表单,我就会按预期收到验证错误,但用户可以将该字段留空,因为这不是必填字段。

PS: i could write my own constraint annotation. However, i just ask an easier way combining annotations or adding annotation attributes. JSR303 implementation is hibernate-validator.

PS:我可以编写自己的约束注释。但是,我只是要求一种更简单的方法来组合注释或添加注释属性。JSR303 实现是休眠验证器。

采纳答案by BalusC

Just set it with nullinstead of empty string. Since empty HTML input fields are by default submitted as an empty string as HTTP request parameter, you need to let your MVC framework interpret empty submitted values as null. This is in JSF easy done by a <context-param>in web.xml. However, since you're using Spring MVC and I don't do it, I searched a bit here and found this answerwhich may be of use.

只需将其设置为null而不是空字符串。由于默认情况下空 HTML 输入字段作为空字符串作为 HTTP 请求参数提交,因此您需要让您的 MVC 框架将空提交的值解释为null. 这在 JSF 中很容易通过<context-param>in完成web.xml。但是,由于您使用的是 Spring MVC 而我不这样做,因此我在这里搜索了一些并找到了可能有用的答案

回答by Gunnar

Another way to address this issue is to allow the empty string as alternative valid value in your regular expression (using "|").

解决此问题的另一种方法是允许空字符串作为正则表达式中的替代有效值(使用“|”)。

As BalusC said in JSF 2 it's possible to convert empty strings automatically to null. The context parameter to use is "javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL", which must be set to "true" (see also this answer).

正如 BalusC 在 JSF 2 中所说,可以将空字符串自动转换为 null。要使用的上下文参数是“javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL”,它必须设置为“true”(另请参阅此答案)。

回答by Shrirang Edgaonkar

Adding a Empty Constraint is the best way to go. In this constraint you add your own @Pattern as the composing constraint.

添加空约束是最好的方法。在此约束中,您添加自己的 @Pattern 作为组合约束。

@Target({ANNOTATION_TYPE, FIELD})
@Retention(RUNTIME)
@Documented
**@Pattern(regexp="...")**
@Constraint(validatedBy = EmptyValueConstraintValidator.class)
public @interface EmptyValueConstraint  {
    String message() default "{defaultMessage}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    @interface List {
        EmptyValueConstraint[] value();
    }
}

public class EmptyValueConstraintValidator  implements     
ConstraintValidator<EmptyValueConstraint, Object>{

    @Override
    public void initialize(EmptyValueConstraint constraintAnnotation) {

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {

        return true;
    }



}

Hope this helps..

希望这可以帮助..