2016-11-18 64 views
2

我創建了自定義表單驗證註釋,以檢查表單中填寫的日期是否爲格式dd/MM/yyyy。不幸的是,它不起作用,驗證失敗,我試着用任何日期格式。最初,我認爲問題是我用來測試的正則表達式,但在做了一些測試之後,我很確定它的工作原理。自定義表單驗證註解不起作用

我錯過了什麼?這裏是我的代碼(我只複製了相關部分),請幫助我理解我做錯了什麼:

豆Articolo(注:這個類是嵌套模型類NewEditArticle內,下同)

@Entity 
@Table (name="Articolo") 
public class Articolo { 

    @Column (name="Data") 
    @Temporal (TemporalType.DATE) //match the data type used in DB 
    @IsValidDate //check date format is dd/MM/yyyy (custom validator) 
    private Date data; 

類IsValidDate

@Documented //mandatory 
@Constraint (validatedBy= DateValidator.class) //this class contains the validation logic 
@Retention (RetentionPolicy.RUNTIME) //mandatory 
public @interface IsValidDate { 

    //error message 
    String message() default "Please insert date in format dd/mm/yyyy"; 

    Class <?>[] groups() default {}; //mandatory 

    Class <? extends Payload> [] payload() default {}; //mandatory 
} 

類DateValidator

public class DateValidator implements ConstraintValidator <IsValidDate, Date > { 

    @Override 
    public void initialize(IsValidDate isValidDate) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public boolean isValid(Date data, ConstraintValidatorContext ctx) { 

     //convert Date data to String 
     String dateString=data.toString(); 

     //format dd/MM/yyyy 
     String regex="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)"; 


     if (dateString.matches(regex)){ 
      return true; 
     } 

     //if date doesn't match regex, return error message from IsValidDate 
     else { 
      return false; 
     } 
    } 

} 

模型類

public class NewEditArticolo { 

    //ATTRIBUTES 

    @Valid //requested to trigger validation of bean Articolo 
    private Articolo articolo; 

    private List<Area> ListaArea; 
    private List<Cucina> ListaCucina; 
    private List<Prezzo> ListaPrezzo; 
    private List<Voto> ListaVoto; 
    private List<String> ListaImg; 


    //METHODS 

    //CONSTRUCTOR 

    //create article model without ID number 
    //used in controller POST method 
    public NewEditArticolo() { 

     populateLists(); 
    } 

    //create Article model based on ID number 
    //if ID=0 (new Article), creates empty model 
    //used in controller GET method 
    public NewEditArticolo(int ID) throws SQLException { 

     // call DAOArticolo.select only if article already exists 
     if (ID != 0) { 
      DAOArticolo DAOart = new DAOArticolo(); 
      articolo = DAOart.select(ID); 
     } 

     populateLists(); 

    } 

控制器

public String editArticle (Model model, 
           @Valid @ModelAttribute (value="nea") NewEditArticolo nea, //create NewEditArticolo object, autowire attributes from ArticleManager.jsp, add to model and validate 
           BindingResult result, //collect validation errors 
           @RequestParam (value="submit") String submit){ //get input value from ArticleManager.jsp 

     Articolo articolo1=nea.getArticolo(); 

     DAOArticolo daoArt = new DAOArticolo(); 

     //if validation fails, return form to display validation errors 
     if (result.hasErrors()) { 
      System.out.println("VALIDATION FAILED"); 
      return "ArticleManager"; 
     } 

     else { 
      System.out.println("VALIDATION WAS SUCCESFULL"); 
     } 

彈簧調度-servlet.xml中

<bean id="messageSource" 
     class="org.springframework.context.support.ResourceBundleMessageSource"> 
     <property name="basename" value="messages" /> 
    </bean> 
+0

您是否確實在類路徑中有了一個bean驗證實現......如果沒有它,將不會發生任何事情。 –

+0

你解決了你的問題嗎? –

+0

不是真的,我不確定你的意思與一個bean驗證實現...你能解釋更多嗎? –

回答

0

你可以做,沒有正則表達式。 Spring有@DateTimeFormat註釋。在你的模型中執行以下操作。

@NotNull(message = "Please enter Birth Date") 
@DateTimeFormat(pattern = "dd/MM/yyyy") 
private Date birthDate; 

您可以添加自定義錯誤消息。在資源文件夾下創建message.properties。在這個文件裏面:

typeMismatch=Invalid date format 

重要的一點是將此添加到配置類。

@Bean 
public MessageSource messageSource() { 
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); 
    messageSource.setBasename("messages"); 
    return messageSource; 
} 
+0

使用基於註解的驗證建議,我總是會得到默認錯誤消息,就像message.properties文件被忽略一樣。我的猜測是,自定義錯誤消息不適用於嵌套對象的驗證,如我的情況(bean class Article是模型類NewEditArticle的字段,它在控制器類中驗證並自動連接到表單)。 –