播放框架选择输入验证 [英] Play framework select input validation
问题描述
我正在使用Play 2.1 我使用助手字段构造函数创建了一个选择下拉框. 下拉框有3个字段,默认为:选择性别",男性"和女性". 如何确保用户选择男性或女性之一,而不选择默认值? (必填的下拉字段)
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)
推荐答案
我正在使用 Play!Framework 2.1.0 ,以下是您遇到的问题的简单解决方案:
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;
}
控制器应如下所示:
/** 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
}
}
模板/视图应如下所示:
@(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">
}
}
另请参阅此帖子作为参考:使用Play Framework 2.0模板中的选项帮助程序
See also this post as reference : Use of option helper in Play Framework 2.0 templates
这篇关于播放框架选择输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!