我正在努力为每个字段只获取一条错误消息。我对每个领域都有很多规则,我想一一验证它们。如果失败,验证将停止并仅返回一条描述该字段失败规则的消息。
经过研究,我发现了类似 @ReportAsSingleViolation 注释的东西,它有点工作,但它修复了来自自定义约束的消息。所以这不是我想要的。
我已经阅读过有关 @GroupSequence 的内容,但我无法让它像我所描述的那样工作。
这是我的具有自定义约束规则的实体:
@Entity
@Table(name = "users", schema = "myschema")
public class User {
private int id;
@ValidLogin
private String login;
@ValidPassword
private String password;
@ValidEmail
private String email;
//getters & setters
}
并使用几个内置规则实现我的自定义约束:
@Constraint(validatedBy = UsernameValidator.class)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@NotEmpty
@Pattern(regexp = "^[a-zA-Z0-9]*$")
@Length.List({
@Length(min = 3 , message = "{Length.min.user.login}"),
@Length(max = 30, message = "{Length.max.user.login}")
})
public @interface ValidLogin {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default { };
}
默认情况下,我会在 jsp View 中收到失败规则的每条消息。所以,我想让它像这样工作:检查规则 @NotEmpty,如果失败,则返回适当的消息,如果不验证下一个规则 @Pattern 等等。
你能帮忙吗?非常感谢!
最佳答案
我想,这就是您正在寻找的内容:
@Test
public void test() {
Validator v = Validation.byProvider( HibernateValidator.class )
.configure()
.buildValidatorFactory()
.getValidator();
// validations for each group - shows only corresponding violations even if other constraints
// are violated as well
assertThat( v.validate( new Bar( null, null ), First.class ) ).hasSize( 2 );
assertThat( v.validate( new Bar( "", "" ), Second.class ) ).hasSize( 2 );
assertThat( v.validate( new Bar( "a", "a" ), Third.class ) ).hasSize( 2 );
// shows that validation will go group by group as defined in the sequence:
//NotNull
Set<ConstraintViolation<Bar>> violations = v.validate( new Bar( null, null ) );
assertThat( violations ).hasSize( 2 );
assertThat( violations ).extracting( "message" ).containsOnly( "must not be null" );
//NotBlank
violations = v.validate( new Bar( "", "" ) );
assertThat( violations ).hasSize( 2 );
assertThat( violations ).extracting( "message" ).containsOnly( "must not be blank" );
//Size
violations = v.validate( new Bar( "a", "a" ) );
assertThat( violations ).hasSize( 2 );
assertThat( violations ).extracting( "message" ).containsOnly( "size must be between 5 and 2147483647" );
}
@GroupSequence({ First.class, Second.class, Third.class, Bar.class })
private static class Bar {
@NotNull(groups = First.class)
@NotBlank(groups = Second.class)
@Size(min = 5, groups = Third.class)
private final String login;
@NotNull(groups = First.class)
@NotBlank(groups = Second.class)
@Size(min = 5, groups = Third.class)
private final String password;
public Bar(String login, String password) {
this.login = login;
this.password = password;
}
}
interface First {
}
interface Second {
}
interface Third {
}
我添加了一个测试,以便可以看到验证是如何逐组进行的。为了实现这样的行为,您需要为您的 bean 重新定义默认组序列。为此,您需要在要验证的 bean 上放置 @GroupSequence 注释,然后列出您需要的所有组,并且不要忘记添加 bean 类本身(如下所示)例子)。所有这些信息也都存在 here - 在文档中。
编辑
如果您同意不使用标准约束,那么您可能会执行以下操作:
@Test
public void test2() throws Exception {
Set<ConstraintViolation<Foo>> violations = validator.validate( new Foo( "", null ) );
assertThat( violations ).hasSize( 2 );
assertThat( violations ).extracting( "message" )
.containsOnly( "value should be between 3 and 30 chars long", "Value cannot be null" );
}
private static class Foo {
@ValidLogin
private final String login;
@ValidLogin
private final String password;
public Foo(String login, String password) {
this.login = login;
this.password = password;
}
}
@Target({ FIELD })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { ValidLogin.ValidLoginValidator.class })
@interface ValidLogin {
String message() default "message";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
class ValidLoginValidator implements ConstraintValidator<ValidLogin, String> {
private static final Pattern PATTERN = Pattern.compile( "^[a-zA-Z0-9]*$" );
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
String message = "";
if ( value == null ) {
message = "Value cannot be null";
}
else if ( !PATTERN.matcher( value ).matches() ) {
message = "Value should match pattern ";
}
else if ( message.length() < 3 || message.length() > 30 ) {
message = "value should be between 3 and 30 chars long";
}
if ( !message.isEmpty() ) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate( message ).addConstraintViolation();
}
return false;
}
}
}
在这种情况下,您只需拥有自己的自定义约束和 validator 。然后你逐个检查,然后根据第一次失败的检查构建违规行为。如果您对登录名和密码执行类似的检查,那么您还可以提取诸如 pattern
和 min
、max
之类的内容作为约束的属性,但对于字符串长度具有不同模式的示例...
关于java - Spring Hibernate 验证 - 每个字段获取一条错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45859113/