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

天涯浪子 提交于 2019-12-23 07:06:24

问题


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

@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.


回答1:


Just set it with null instead 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 answer which may be of use.




回答2:


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).




回答3:


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

@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..



来源:https://stackoverflow.com/questions/5998978/how-to-use-pattern-on-non-mandatory-fields-jsr-303

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!