Search code examples
javaplayframeworkplayframework-2.2

Play framework, Different constraints for different requests


How to implement different constraints for different requests? For example, there is User class:

public class User extends Model{
  @Required
  @Email
  @Id
  public String email;

  @Required
  @Column(length = 50)
  public String firstname;

  @Required
  @Column(length = 50)
  public String lastname;

  @Required
  public String password;
}

When I create a new user, all constraints are required. But when I update user information, I don't need the password constraint.

Should I create separate classes for createUser() and updateUser() actions? Is there any way I can use just one class?


Solution

  • As Play's validation framework conforms to the Java bean validation specification (JSR-303), you can use the validation groups feature that is part of the spec. This is exactly what you are looking for - a neat way of enforcing different validation rules for different actions. You can see an example of how to use it in code in this answer I gave to a similar question.