我在Play 2.3.7框架项目中有以下Address.java类,但自定义验证函数validate()检查国家/地区字段的输入是否有效。
字段国家/地区应仅接受:" 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 :(得分:0)
这是表单中的顶级对象还是嵌套对象? validate
仅在顶级对象上执行。