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);
        }
    }
}

详细内容参考官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值