Bean validation specification prioritizing

独自空忆成欢 提交于 2020-01-15 09:24:28

问题


I am using bean validation specification to validate my form on spring-boot thymeleaf project. My entity property is as follow.

@NotEmpty(message = "{Password should not be empty}")
@Pattern(regexp = //Pattern for range 1-20, message = "{Wrong Input}")
private String            password;

When I run and inputed to password field of my form with empty value, both of Validation Error Messages were shown.

My expectation is, while empty value is inputed, only @NotEmpty annotation should work and on the other hand, only @Pattern should be shown upon user input is wrong.

How can I do with Bean Validation Specification for that?

Regards.


回答1:


1. Validation groups

@NotEmpty(groups = First.class), message = ...,          
@Pattern(groups = Second.class, regexp = ...)
private String password;

Create the validation groups:

//Validation Groups - Just empty interface used as Group identifier
public interface First {
}
public interface Second {
}

and validate the model this way:

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Model>> violations = validator.validate(model, First.class);

if(violations.isEmpty()){
     violations = validator.validate(model, Second.class);
}

2. Groups Sequences

I've never used them, but it seems it does just what you want

Check this other answer (https://stackoverflow.com/a/7779681/641627). I've added below a quote from this answer (from @Gunnar), which ironically also uses First and Second group names:

@GroupSequence({First.class, Second.class})
public interface Sequence {}

@Size(min = 2, max = 10, message = "Name length improper", groups = { First.class })
@Pattern(regexp = "T.*", message = "Name doesn't start with T" , groups = { Second.class })
private String name;

When now validating a Bean instance using the defined sequence (validator.validate(bean, Sequence.class)), at first the @Size constraint will be validated and only if that succeeds the @Pattern constraint.

With this solution, you wouldn't need to manually call validator.validate(...), the validations would be performed in the order defined in the Sequence with short-circuit if one fails.



来源:https://stackoverflow.com/questions/41596587/bean-validation-specification-prioritizing

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