Play Framework 2: Best way of validating individual model fields separately

我怕爱的太早我们不能终老 提交于 2019-12-05 09:29:49

Play's in-built validation annotations conform to the Java bean validation specification (JSR-303). As a result, you can use the validation groups feature documented in the spec:

Model

@Entity
public class User extends Model {

  // Use this interface to mark out the subset of validation rules to run when updating a user's first name
  public interface FirstNameStep {}

  @Id
  public Long id;

  @Required(groups = FirstNameStep.class)
  public String firstName;

  // This isn't required when updating a user's first name
  @Required
  public String lastName;
}

Controller

public class UsersController {

  public static Result updateFirstName() {

    // Only run the validation rules that need to hold when updating a user's first name
    Form<User> filledForm = Form.form(User.class, User.FirstNameStep.class).bindFromRequest();

    if (form.hasErrors()) {
      // return bad request with errors as json
    }

    // else save and return ok()
  }
}

Validation groups are intended for your situation, where you have the same model object backing different forms, and you want to enforce different validation rules for the forms.

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