thinkphp5.0自定义验证规则使用方法

2025-05-27 0 37

我们在用thinkphp5.0时候,经常要自定义验证规则,这个写法与tp以前的版本有所区别,小编今天带来大家一起来学习一下5.0下验证规则的使用方法。

thinkphp5中定义$rule(验证规则)有两种方式

方式一:

?

1

2

3

4

5
$rule = [

// 不可以在此处定义空的验证 如 'name' => '',会导致出现result未定义错误

'name' => 'require|max:25',

'age' => 'number|between:1,120',

];

方式二:

?

1

2

3

4
$rule = [

'name' => ['require','max'=>25],

'age' => ['number','between'=>'1,120'],

];

如果方式一自定义验证规则的话,就可以这样写

?

1

2

3

4

5

6

7

8
$rule = [

'name' => 'require|max:25|checkName:',

'age' => 'number|between:1,120',

];

protected function checkNmae($value)

{

$value 是name值,可以在此处进行验证,如正则验证

}

如果是方式二的话,写法如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
$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;

}

}

以上就是我们给出的两种方法的代码,如果你有更好的方法或者代码可以在下面的留言区讨论留言。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 thinkphp5.0自定义验证规则使用方法 https://www.kuaiidc.com/71813.html

相关文章

发表评论
暂无评论