2013-02-27 91 views
0

我正在使用播放2.1 我使用助手字段構造函數做了一個選擇下拉框。 下拉框有3個字段,默認值:「選擇性別」,男性和女性。 如何確保用戶選擇男性或女性之一,而不是默認值? !(A所需的下拉場)播放框架選擇輸入驗證

回答

1

我使用播放框架2.1.0,下面是你的問題一個簡單的解決方案:

模式應該是這樣的:(下面是簡單的模型您的問題)

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"> 
    } 
} 

參見這篇文章作爲參考:Use of option helper in Play Framework 2.0 templates