thinkPHP5使用验证器规则between时所遇问题
先看示例:
<?php namespace app\index\validate; use think\Validate; class User extends Validate { protected $rule = [ 'email' => 'email', 'name' => 'chsDash|between:2,12', ]; protected $message = [ 'email' => '邮箱格式错误', 'name.chsDash' => '昵称只允许汉字、字母、数字和下划线_及破折号-', 'name.between' => '昵称长度只能在2-12之间', ]; protected $scene = [ 'email' => ['email'], 'add' => ['name'], ]; }
<?php namespace app\index\controller; use think\Controller; class Test extends Controller { public function index(){ $data = ['name' => '123456']; $validate = validate('User'); if(!$validate->scene('add')->check($data)){ dump($validate->getError()); } } }
按上述代码,页面模板显示如下:
![](http://runtuchigua.cn/wp-content/uploads/2021/07/QQ截图20210705170144.png)
随后又将name改为了字母,汉字,长度不一,各种测试。
结果显示,在name等于2~12之间时,才不会报错。
之所以如此,是因为我误解了between的用法,between的作用只能验证数字是否在规定的范围内,并不能验证字符的长短。
length才是检验字符串长短的
修改代码如下:
<?php namespace app\index\validate; use think\Validate; class User extends Validate { protected $rule = [ 'email' => 'email', 'name' => 'chsDash|length:2,12', ]; protected $message = [ 'email' => '邮箱格式错误', 'name.chsDash' => '昵称只允许汉字、字母、数字和下划线_及破折号-', 'name.length' => '昵称长度只能在2-12之间', ]; protected $scene = [ 'email' => ['email'], 'add' => ['name'], ]; }
总结:一定要仔细阅读开发文档,避免下意识决断