Found a (temporary) solution to use the same validation annotations on the client and on the server with RequestFactory:
Put the JSR 303 annotations in a separate interface that is implemented by both the proxy interface (client) and the domain classes (server). This interface must be in the shared package, of course.
Since the validation annotations will automatically be passed down the inheritance hierarchy, validation should now work on the client as well as on the server.
Example
Here is an example of an object used when a User attempts to register:
UserProxyValid
is the common interface containing the JSR 303 validation annotations:
public interface UserProxyValid {
@NotBlank(
groups = {ClientGroup.class, ServerGroup.class})
@UniqueEmail(
groups = {ServerGroup.class})
String getEmail();
@NotBlank(
groups = {ClientGroup.class, ServerGroup.class})
@Size(
min = 4, max = 25,
groups = {ClientGroup.class, ServerGroup.class})
String getPassword();
}
User
is the domain class on the server:
public class User implements UserProxyValid {
private String email;
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And finally the UserProxy
for the client:
@ProxyFor(value = User.class)
public interface UserProxy extends ValueProxy, UserProxyValid {
String getEmail();
void setEmail(String email);
String getPassword();
void setPassword(String password);
}
Groups
With groups we can make shure that individual validations are either done on the client or on the server only or on both. (As in the example above, validation on uniqueness of email can only be done on the server.)
This is how you would validate an object on the client:
Validator clientValidator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<UserProxy>> violations = clientValidator.validate(userProxy, ClientGroup.class);
And here is how validation is done on the server:
Validator serverValidator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<User>> violations = serverValidator.validate(user, ServerGroup.class);
Hope for the Future
Of course, it would be better without the additional UserProxyValid
class. So as soon as Google provides an update on BeanValidation, we might be able to eliminate that class and move the annotations to the domain class.