Validate elements of a String array with Java Bean Validation

纵然是瞬间 提交于 2019-11-29 14:19:02

By adding the @Valid annotation like you've done, the validation algorithm is applied on each element (validation of the element constraints).

In your case the String class has no constraints. The @Pattern constraint you've added is applied to the array and not on each element of it. Since @Pattern constraint cannot be applied on a array, you are getting an error message.

You can create a custom validation constraint for your array (see Hibernate docs for more info) or you can use a wrapper class like @Jordi Castilla mentioned.

Franck

Another thing worth mentioning is the introduction of type annotation in Java 8 which lets you annotate parameterized type

private List<@MyPattern String> defaultAppAdminRoles;

It's not yet in the bean-validation standard (surely in next version) but already available in hibernate-validator 5.2.1. Blog entry here for further information.

Jordi Castilla

First... i'm not sure... but @Pattern only accepts regex, right? Correct sintax is not:

@Pattern("^[_ A-Za-z0-9]+$")   // delete 'regexp='

If this is not the problem you can create a wrapper class with validators in the attributes:

public class Role {

    @Pattern(regexp="^[_ A-Za-z0-9]+$")
    String adminRole;

    //getters and setters
}

Then just need to mark the field @Valid in your existing object:

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