2017-08-11 34 views
1

我正在使用Hibernate驗證器API進行服務器端驗證,其中一個表的名稱爲Supplier_Registration。相應的Java類如下所示。其中一個成員是另一個叫做Address的類。我需要對Address使用哪些註釋,以便Address類的成員也得到驗證?非常感謝。使用Hibernate驗證器的另一個類中的類的註釋

public class Registration implements Serializable { 
    private static final long serialVersionUID = 3380401999460628270L; 
    private static final String EMAIL_PATTERN = 
      "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" 
      + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; 

    @NotNull(message="{legalName_notnull}") 
    @Size(min=1, max=255, message="{legalName_not_to_exceed}") 

    private String legalName; 

    @NotNull(message="{adminFirstName_notnull}") 
    @Size(min=1, max=40, message="{adminFirstName_not_to_exceed}") 
    private String adminFirstName; 


    @NotNull(message="{adminLastName_notnull}") 
    @Size(min=1, max=40, message="{adminLastName_not_to_exceed}") 
    private String adminLastName; 

    @NotNull(message="{adminEmail_notnull}") 
    @Size(min=1, max=255, message="{adminEmail_not_to_exceed}") 
    @Pattern(regexp=EMAIL_PATTERN, message="{adminEmail_not_valid}") 
    private String adminEmail; 

    @NotNull(message="{reEnterEmail_notnull}") 
    @Size(min=1, max=255, message="{reEnterEmail_not_to_exceed}") 
    @Pattern(regexp=EMAIL_PATTERN, message="{reEnterEmail_not_valid}") 

    private String reEnterEmail; 

    @NotNull(message="{phoneCountryNumber_notnull}") 
    @Size(min=1, max=5, message="{phoneCountryNumber_not_to_exceed}") 
    private String phoneCountryNbr; 

    @NotNull(message="{phoneNumber_notnull}") 
    @Size(min=1, max=18, message="{phoneNumber_not_to_exceed}") 
    private String phoneNumber; 

    @NotNull(message="{dunsNumber_notnull}") 
    @Size(min=1, max=9, message="{dunsNumber_not_to_exceed}") 
    private String dunsNumber; 

    private Address address; 

回答

0

您要執行的這種驗證稱爲級聯驗證。要驗證address,您需要在address屬性上使用@Valid註釋。另外,如果address是強制性的(意思是如果該字段不能爲空),那麼也可以使用@NotNull。所以,你有這樣的事情:

public class Registration implements Serializable { 
    // all other properties ... 

    @Valid // this one is requred if you want address constraints to be validated 
    @NotNull // this one is optional - use it in case if address is a mandatory field 
    private Address address; 
} 

約級聯驗證的所有信息,你可以在這裏的文檔中找到 - Object graphs

相關問題