十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这篇文章主要讲解了“thinkphp5.0自定义验证规则的使用方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“thinkphp5.0自定义验证规则的使用方法”吧!

我们在用thinkphp5.0时候,经常要自定义验证规则,这个写法与tp以前的版本有所区别,小编今天带来大家一起来学习一下5.0下验证规则的使用方法。
在thinkphp5中定义$rule(验证规则)有两种方式
方式一:
$rule = [ // 不可以在此处定义空的验证 如 'name' => '',会导致出现result未定义错误 'name' => 'require|max:25', 'age' => 'number|between:1,120', ];
方式二:
$rule = [ 'name' => ['require','max'=>25], 'age' => ['number','between'=>'1,120'], ];
如果方式一自定义验证规则的话,就可以这样写
$rule = [
'name' => 'require|max:25|checkName:',
'age' => 'number|between:1,120',
];
protected function checkNmae($value)
{
$value 是name值,可以在此处进行验证,如正则验证
}如果是方式二的话,写法如下
$rule = [
'name' => ['require','max'=>25,'checkName'=>'$rule参数'],
'age' => ['number','between'=>'1,120'],
'email' => ['require', 'checkUserEmail'=>'qq.com'],
];
protected function checkName($value, $rule)
{
$vaule 是name值,$rule为上面的$rule参数
}
protected function checkUserEmail($value,$rule)
{
$res = preg_match('/^\w+([-+.]\w+)*@'.$rule.'$/', $value);
if (!$res) {
return '邮箱只能是'.$rule.'域名';
} else {
return true;
}
}感谢各位的阅读,以上就是“thinkphp5.0自定义验证规则的使用方法”的内容了,经过本文的学习后,相信大家对thinkphp5.0自定义验证规则的使用方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联网站建设公司,,小编将为大家推送更多相关知识点的文章,欢迎关注!