2013-03-07 17 views
0

在當前項目中,我在模型bean上的電話號碼在3個字段中,但我們只想要一個彈簧驗證錯誤。可以這樣做>電話號碼是在春天模型中的3個字段,但我只想要一個驗證錯誤

@NotEmpty(message = "Your Question must not be blank.") 
@Size(min = 10, max = 200) 
private String content; 

@NotEmpty(message = "Area Code must not be blank.") 
@Size(min = 3, max = 3, message = "Area must be 3 numbers") 
private String areacode; 

@NotEmpty(message = "Phone Number must not be blank.") 
@Size(min = 3, max = 3, message = "phone number first part must be 3 numbers") 
private String phone3; 

@NotEmpty(message = "Phone Number must not be blank.") 
@Size(min = 4, max = 4, message = "Phone number last part must be 4 numbers") 
private String phone4; 
+0

您有兩種選擇:1)從每個電話號碼字段中刪除您的驗證,而是創建一個[JSR-3030類級約束](http://docs.jboss.org/hibernate/validator/ 4.3/reference/en-US/html_single /#d0e341)可以一起驗證所有字段。或者2),因爲你使用的是Spring,你可以編寫一個[Spring Validator](http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference)。 html#validator)。如果您準備開發開發工具,我會傾向於使用JSR-303約束。 – sbk 2013-03-07 15:32:18

回答

1

如果每當驗證錯誤發生在類級別不要緊,但不能在外地,那麼你可以使用Hibernate的驗證ScriptAssert驗證

@ScriptAssert(
    lang="javascript" 
    script="_this.areacode!=null and _this.phone3!=null and _this.phone4!=null" 
) 
public class YourClass { 
    private String areacode; 
    private String phone3; 
    private String phone4; 
} 

更多的其他想法看看跨領域驗證討論/問題。 Cross field validation with Hibernate Validator (JSR 303)