游戏框架2.5中的ebean验证

时间:2016-11-20 04:00:05

标签: playframework ebean playframework-2.5

我正在查看他们页面上提供的示例代码:

@Entity
public class Task extends Model {

    @Id
    @Constraints.Min(10)
    public Long id;

    @Constraints.Required
    public String name;

    public boolean done;

    @Formats.DateTime(pattern="dd/MM/yyyy")
    public Date dueDate = new Date();

    public static Finder<Long, Task> find = new Finder<Long,Task>(Task.class);
}
@ Constraints.Min(10)似乎不起作用。当我尝试使用约束开发我的模型时,它没有在保存时触发验证。示例代码:

@Entity
public class Company extends Model{

    private static final long serialVersionUID = 1L;

    @Id
    public Long id;

    @Column(columnDefinition = "varchar(100)", nullable false)
    @Constraints.Required
    @Formats.NonEmpty
    @Constraints.MinLength(10)
    @Constraints.MaxLength(10)
    public String name;

}

我尝试运行此代码:

Company company = new Company();

company.name="";
company.save()

虽然名称为空字符串,但它会将数据保存到数据库中。

1 个答案:

答案 0 :(得分:0)

约束是用于表单绑定验证,而不是直接字段设置。

private static final Form<Company> companyForm = formFactory.form(Company.class);

所以在渲染视图的控制器方法中。

Form<Company> filledForm = companyForm.fill(company);
view.render(filledForm);

在处理回发到服务器的表单的控制器方法中。

Form<Company> boundForm = companyForm.bindFromRequest();
if (boundForm.hasErrors()) {
    // This will happen if there is validation errors, you can also add a validate method to Company for more complex validation
    return badRequest(views.html.form.render(boundForm));
} else {
    Company company = boundForm.get();
    return ok("Got company " + company);
}