undefinedfix
Sign in

Problems of user defined verification in TP5

tstrub edited in Sat, 19 Feb 2022

For example, arrays look like this

$data = [
    [
        'mobile'=> '手机号码1',
        'price' => '100.00'
    ],
        [
        'mobile'=> '手机号码2',
        'price' => '500.00'
    ],
];

One dimensional array can be verified directly

  protected $rule = [
    'mobile'=> 'require|mobile',
  ]

But now it's a two-dimensional array. TP has custom verification. What I want to verify now is that the mobile phone number in the array must have a value and must be a legal mobile phone number. The amount must be a positive integer or two digits after the decimal point!

Custom validation:

  protected $rule = [
    'mobile'=> 'require|array|checkMobile',
  ]
//自定义验证函数
protected function checkMobile()
{
  //在这里面咋使用验证呢?
  //最好是可以使用Tp自带的规则 比如mobile require unique等!!!!
}
2 Replies
cylda
commented on Sat, 19 Feb 2022
//自定义验证函数
    protected function checkMobile($value)
    {
        # 01: 首先循环当前数据  每一项的值(value)
        # 02: 之后将该值赋给 变量mobile
        # 03: 之后使用写验证规则和错误信息
        # 04: 之后将错误信息给$this->message();
        # 05: 最后验证  $this->check(验证数据,验证规则);
        # 06: 最后判断 如何为false 就返回错误信息 $this->getError();
        foreach ($value as $item) {
            $data['mobile'] = $item;
            $rules = [
                'mobile' => 'require|mobile',
            ];
            $message = [
                'mobile.require' => '手机号码不得为空!',
                'mobile.mobile' => '手机号码格式错误!',
            ];
            if (false === $this->message($message)->check($data, $rules)) {
                return $this->getError();
            } else {
                return true;
            }
        }
    }

When using:

    protected $rule = [
        'mobile' => 'require|checkMobile',
    ];

The data are as follows:

$data = [
    [
        'mobile'=> ['手机号码1','手机号码2'],
    ];
];
Nahuel
commented on Sat, 19 Feb 2022

Emmm, foreach to call the abstract independent validator, a little thought, I saw the previous TP5 small project, it seems that at most is a bit array verification, I hope to help you

lock This question has been locked and the reply function has been disabled.