Play中的验证方式
每个请求都有自己的Validation对象,该对象收集错误。
有三种验证方式:
- 直接使用 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);
}
}
}