2015-01-08 33 views
0

我在Play 2.3.7框架項目中有以下Address.java類,但自定義驗證函數validate()檢查country字段的輸入無效。Play 2.3.7框架表單不工作的自定義驗證

字段國家應該只接受:「AR」,「BE」或「SL」。但現在它實際上接受任何2個字符的字符串,這意味着驗證不起作用。

任何人都可以請告訴這裏有什麼問題嗎?

package models; 

import play.data.*; 
import play.data.validation.Constraints.*; 

import javax.persistence.*; 

@Entity 
public class Address extends play.db.ebean.Model { 

    @Id 
    @GeneratedValue 
    public Long internalId; 

    //CUSTOM :: Sample implementation of Hard Coded data 
    public enum Country { 
    ARDA("Arda", "AR"), 
    BELGIUM("Belgium", "BE"), 
    SMURFS_LAND("Smurfs Land", "SL"); 

    public String name; 
    public String id; 
    private Country(String name, String id) { 
     this.name = name; 
     this.id = id; 
    } 

    public static Country getById(String id) { 
     for (Country c: values()) { 
     if (c.id.equals(id)) { 
      return c; 
     } 
     } 
     throw new IllegalArgumentException("Country not found => Bad id {"+id+"}"); 
    } 
    } 



    @Required 
    @Pattern(
    value="[A-Z]{1}\\w*, [0-9]+", 
    message="A street starts with an upper case, and ends with a number after a comma" 
) 
    public String fullStreet; 

    @Required 
    public String county; 

    @Required 
    @MaxLength(2) 
    public String country; 

    //CUSTOM :: validation rules 
    public String validate() { 
    try { 
     Country.getById(country); 
     return null; 
    } catch (IllegalArgumentException e) { 
     return "Bad country : " +country; 
    } 
    } 


} 

回答

0

這是表單中的頂層對象還是嵌套對象? validate僅在頂層對象上執行。

+0

謝謝詹姆斯。是的,你說得對,地址是用戶(頂級對象)的嵌套對象,這是它的類http://pastebin.com/Kv2aAC26。我試圖通過一些修改將驗證移動到User類,但它不起作用。我還試圖爲用戶類內的名稱字段編寫一個不同的validate()函數,但仍然提交表單,就好像驗證是一樣的不在那裏。 – beeko

+0

這是驗證()我在用戶類上測試:public String validate(){ if(name!=「Tom」){ \t return「invalid name」; } else { \t return null; } } – beeko