简体   繁体   中英

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?

It is bad practise to mix "back-end entity" annotations with "front-end entity" annotations. Create separate class for inserting user and updating user with @Required annotations accordingly. Remove front-end annotations from User entity and leave only JPA annotations like @Id @Column etc.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM