PHP code example of hehex / hehep-hvalidation

1. Go to this page and download the library: Download hehex/hehep-hvalidation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hehex / hehep-hvalidation example snippets



// 验证器参数
$validatorConf= [
    "message"=>"你输入的格式错误!",// 错误消息,
    "err_code"=>null,// 错误码,非必填
    "skipOnEmpty"=>true,// 当验证值为空时是否调用验证,true 表示值为空时不验证,false 表示值为空时继续验证
];

// 验证规则参数
$ruleConf = [
    "goon"=>false,// 当验证失败后,是否继续其他验证
    "message"=>"你输入的格式错误!",// 错误消息
    "err_code"=>null,// 错误码,非必填
    "on"=>"create",// 使用场景
    "when"=>'valint(方法或函数)',// 满足条件,规则才有效
];

use hehe\core\hvalidation\Validation;
$hvalidation = new Validation();

// 校验数据
$data = [
    'name'=>"hehe",// 用户姓名
    'age'=>2,// 年龄
    'userType'=>1,// 用户类型
    'tel'=>'138xxxxxxxxx',// 联系方式
];

// 校验规则
$rules = [
    ['name',[['r',['phone'],['mobile']],'message'=>'请输入手机号或固定电话'],
    
];

$validationResult = $hvalidation->validate($rules,$data);
if (!$validationResult->getResult()) {
    var_dump("校验失败");
    // 获取首个验证器错误消息
    var_dump($validationResult->getFirstError());
    var_dump($validationResult->getFirstCode());
} else {
    var_dump("校验成功");
}

// 验证是否手机
Validation::tel('135xxxxxxx');

// 验证是否ip
Validation::ip('135xxxxxxx');


$rules = [
    ['attr1',[['an'],['minlen','min'=>10,'max'=>20]],'message'=>'请输入一个10-20位的字符串或布尔型'],
]

$rules = [
    ['attr1',['&' [['验证器1']],['or',[['验证器2']],[['验证器3']]] ],'message'=>'多验证器,或'],
]


$rules = [
    ['attr1,attr2',[['!empty']],'message'=>'参数不能为空'],
]

//@todo

$rules = [
    ['attr1',[['

$rules = [
    ['attr1',[['

// on=add 用于添加规则
$rules = [
    ['attr1',[['

/**
 * @param $rule 当前规则对象
 * @param $attrs 传入的所有数据
 */
function whencon($rule,$attrs) {
    return true;
}

$rules = [
    ['attr1',[['

use hehe\core\hvalidation\Validation;
$hvalidation = new Validation();
$validation->addValidator('自定义验证器别名','hehe\\core\\validate\\BooleanValidate','自定义消息内容');

$rules = [
     ['attr1',[ [[$this,'func1'] ] ],'message'=>'请输入一个10-20位的字符串']
];

$rules = [
     ['attr1',[ [function($val,CallValidator $validator){
        // 验证结果 true or false
        
        // 定义的其他参数
        $validator->params;
        
     } ] ],'message'=>'请输入一个10-20位的字符串']
];

use hehe\core\hvalidation\Validation;
$result = Validation::number('12',['name'=>23232]);
// result : true or false

use hehe\core\hvalidation\Validation;
$validation = new Validation();
$validate = $validation->createValidator('range',['min'=>10,'max'=>20]);
$result = $validate->validate(20);
// result : true or false

use hehe\core\hvalidation\annotation\RequiredValid;
use hehe\core\hvalidation\annotation\RangeLengthValid;
use hehe\core\hvalidation\annotation\EgtValid;

class IndexController
{
    /**
     * @var string
     * @RequiredValid("不能为空")
     * @RangeLengthValid(min=10,max=20)
     */
     public $name;
    
    /**
     * @var string
     * @RequiredValid("不能为空")
     * @EgtValid(number=10)
     */
     public $age;

}


/**
 * 自定义验证器
 * Class CommonValidators
 * @package common\extend\validators
 */
class CommonValidators
{
    // 定义
    public static function install()
    {
        return [
            'tel'=>['class'=>'common\extend\validators\TelValidators'],
            // 静态方法调用
            'ip'=>['class'=>'CallValidator','func'=>'common\extend\validators\CommonValidators@@ip'],
            // 对象方法调用
            'ip6'=>['class'=>'CallValidator','func'=>'common\extend\validators\CommonValidators@ip6'],
            //'ip'=>['class'=>'CallValidator','func'=>[static::class,'ip']],
        ];
    }

    public static function ip($value)
    {

        $valid = preg_match('/^(\d+\.\d+\.\d+\.\d+)$/', $value);

        return $valid === 1;
    }

    public function ip6($value)
    {

        $valid = preg_match('/^(\d+\.\d+\.\d+\.\d+)$/', $value);

        return $valid === 1;
    }
}

namespace common\extend\validators;
use hehe\core\hvalidation\base\Validator;

class TelValidator extends Validator
{
    public static function install()
    {
        return [
            'tel'=>['class'=>static::class,'其他规则'=>'xxxx'],
        ];
    }
    
    protected $pattern = '/^1[0-9]{10}$/';

    protected function validateValue($value,$name = null)
    {
        $valid = preg_match($this->pattern, $value);

        return $valid === 1;
    }
}

// 创建Validation 对象后,自动加载CommonValidators 类定义的验证规则
$hvalidation = new Validation([
        'customValidators'=>[
            'common\extend\validators\CommonValidators',// 需安装的验证器集合类
            [dirname(__FILE__),'\common\extend\validators'] // ['安装的目录','目录对应的命名空间']
        ]
]);

// 安装的方式
Validation::install('common\extend\validators\CommonValidators');


Validation::install('common\extend\validators\CommonValidators');


Validation::install('common\extend\validators\CommonValidators',true);


Validation::install('common\extend\validators\CommonValidators',true,true);


Validation::install('common\extend\validators\CommonValidators',true,false,'validators');


// 目录下所有验证器都会被安装
Validation::install([
    dirname(__FILE__),// 安装的目录
    '\common\extend\validators',目录对应的命名空间
]);


namespace hvalidation\tests\common;
use hehe\core\hvalidation\annotation\RequiredValid;
use hehe\core\hvalidation\annotation\NumberValid;
use hehe\core\hvalidation\annotation\InlistValid;
use hehe\core\hvalidation\annotation\Validator;
use hehe\core\hvalidation\annotation\MobileValid;

class UserController
{
    /**
     * @RequiredValid("姓名不能为空")
     * @var string
     */
    public $name;

    /**
     * @RequiredValid("请填写年龄")
     * @NumberValid("请输入的年龄格式错误")
     * @var string
     */
    public $age;

    /**
     * @RequiredValid("请选择用户类型")
     * @InlistValid("用户类型的值必须为1,2,3,4!",numbers="1,2,3,4")
     * @var string
     */
    public $userType;

    /**
     * @MobileValid("手机号码",numbers="1,2,3,4")
     * @var string
     */
    public $tel;

    /**
     * @RequiredValid(message="姓名不能为空",name="name")
     * @RequiredValid("姓名不能为空",name="age")
     * @NumberValid("请输入的年龄格式错误",name="age")
     * @RequiredValid("请选择用户类型",name="userType")
     * @InlistValid("用户类型的值必须为1,2,3,4!",name="userType",numbers={1,2,3,4})
     * @Validator("手机号码",name="tel",validator={"or",{"mobile"},{"phone"}})
     */
    public function add(){}

    /**
     * @RequiredValid("姓名不能为空",name="name")
     * @RequiredValid("姓名不能为空",name="age")
     * @NumberValid("请输入的年龄格式错误",name="age")
     * @RequiredValid("请选择用户类型",name="userType")
     */
    #[InlistValid(message:"用户类型的值必须为1,2,3,4!",name:"userType",numbers:"1,2,3,4")]
    #[Validator("联系电话错误",name:"tel",validator:array('or',array('mobile'),array('phone')))]
    public function add1(){}
}

use hehe\core\hvalidation\Validation;
 // 验证数据
$data = [
    'name'=>"hehe",// 用户姓名
    'age'=>2,// 年龄
    'userType'=>4,// 用户类型
    'tel'=>'13811111111',// 联系方式
];


$hvalidation = new Validation();
// 获取UserController 类属性的验证规则
$rules = Validation::getRule(UserController::class);
$rules = $hvalidation->getClassRule(UserController::class);

// 获取UserController类add方法的验证规则
$rules = $hvalidation->getMethodRule(UserController::class,'add');
$rules = Validation::getRule(UserController::class . '@add');


$validationResult = $hvalidation->validate($rules,$data);