Play Framework 1.4 學習筆記 表單驗證,驗證Http數據

Play中的驗證方式

每個請求都有自己的Validation對象,該對象收集錯誤。
有三種驗證方式:

  1. 直接使用 validation.required(…)
public static void hello(String name, Integer age) {
     validation.required(name);
     validation.required(age);
     validation.min(age, 0);
     
     if(validation.hasErrors()) {
         for(Error error : validation.errors()) {
             System.out.println(error.message());
         }
     }
}

2.使用@Required註解

public static void hello(@Required String name, @Required @Min(0) Integer age) {
   if(validation.hasErrors()) {
       params.flash(); // add http parameters to the flash scope
       validation.keep(); // keep the errors for the next request
       index();
   }
   render(name, age);
}

3.使用@Valid註解

public class User {
    
    @Required
    public String name;
 
    @Required
    @Min(0)
    public Integer age;
}

public static void hello(@Valid User user) {
   if(validation.hasErrors()) {
       params.flash(); // add http parameters to the flash scope
       validation.keep(); // keep the errors for the next request
       index();
   }
   render(name, age);
}

在模板中顯示錯誤

#{ifErrors}
   <h1>Oops…</h1>
   #{errors}
       <li>${error}</li>
   #{/errors}
#{/ifErrors}

#{else}
   Hello ${name}, you are ${age}.
#{/else}

自定義錯誤消息

1.conf/message validation.required = 這是必填項
2. 也可以使用佔位符 validation.required=%s 是必須的
3. 使用@Required(message="")

自定義驗證

public class User {
    
    @Required
    @CheckWith(MyPasswordCheck.class)
    public String password;
    
    static class MyPasswordCheck extends Check {
        
        public boolean isSatisfied(Object user, Object password) {
            return notMatchPreviousPasswords(password);
        }
    }
}

詳細內容參考官方文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章