Play framework select input validation

2019-06-13 03:30发布

I am using Play 2.1 I made a select drop down box using the helper field constructor. The drop down box have 3 fields, default:"choose a gender", Male, and Female. How do I ensure that the user choose one of male or female, and not the default value? (A required drop down field)

1条回答
Melony?
2楼-- · 2019-06-13 04:03

I am using Play!Framework 2.1.0, below is a simple solution for your problem:

The model should be like this: (Below is simple model for your problem)

package models;

import play.data.validation.Constraints;

public class Gender {
   // This field must have a value (not null or not an empty string)
   @Constraints.Required
   public String gender;
}

The controller should be like this:

/** Render form with select input **/
public static Result selectInput() {
   Form<Gender> genderForm = Form.form(Gender.class);

   return ok(views.html.validselect.render(genderForm));
}

/** Handle form submit **/
public static Result validateSelectInput() {
   Form<Gender> genderForm = Form.form(Gender.class).bindFromRequest();

   if (genderForm.hasErrors()) { // check validity
      return ok("Gender must be filled!"); // can be bad request or error, etc.
   } else {
      return ok("Input is valid"); // success validating input
   }
}

The template/view should be like this:

@(genderForm: Form[models.Gender])
@import views.html.helper._

@main(title = "Validate Select") {
   @form(action = routes.Application.validateSelectInput()) {
      @********** The default value for select input should be "" as a value *********@
      @select(
         field = genderForm("gender"),
         options = options("" -> "Select Gender", "M" -> "Male", "F" -> "Female")
      )

      <input type="submit" value="Post">
   }
}

See also this post as reference : Use of option helper in Play Framework 2.0 templates

查看更多
登录 后发表回答