-1

I was looking at the sample code provided on their page :

@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);
}

the @Constraints.Min(10) does not seem to be working. When I tried to develop my model with a constraints, it did not trigger the validation upon saving. sample code:

@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;

}

and I tried to run this code :

Company company = new Company();

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

it will save the data into the database although the name was empty string.

Lee
  • 1
  • 4

1 Answers1

0

The Constraints are for form binding validation, not direct field setting.

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

So in the controller method that renders the view.

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

In the controller method that handles the form posting back to the server.

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);
}
Shanness
  • 365
  • 2
  • 10
  • 1
    is there anyway to do field validation for ebean? – Lee Nov 30 '16 at 12:55
  • Sorry for the late reply. Seems you can use `javax.validation.constraints` constraints such as `@Size(min=10)` (for string etc lengths), or in your case (a number), `@Min(10)` with modern versions of ebean. I haven't tested it, but it seems like it will do what you want. – Shanness Dec 04 '16 at 14:26
  • https://docs.oracle.com/javaee/7/api/javax/validation/constraints/package-summary.html – Shanness Dec 04 '16 at 14:33