在构建小程序验证规则的时候,如果使用的规则是TP5的内置规则如(require)可以直接使用,如果想用的验证TP5没有提供内置规则,则需要自己编写验证规则。
编写自定义验证规则是非常重要的技术
用验证器的思路来编写自定义验证规则,代码如下:
class IDMustBePositiveInt extends Validate
{
protected $rule = [
'id' => 'require|isPositiveInteger' //require 是内置验证规则;isPositiveInteger是自定义验证规则(自定义验证规则的使用和内置验证规则的使用方法是一样的)
];
protected function isPositiveInteger($value, $rule = '', $data = '', $field = '') //将isPositiveInteger 定义为 protect属性的函数 (参数:value,是传递进来的需要验证的参数;rule,不常用,data,是需要验证的数组;field,参数是参数的名称)
{
if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0){(is_numberic($value),判断是否为数字)
return true;
}
else{
return $field.'必须是正整数';
}
}
}
网友评论