鍍金池/ 問答/PHP  Python/ Tp5中自定義驗證的問題

Tp5中自定義驗證的問題

例如 數(shù)組是這樣的

$data = [
    [
        'mobile'=> '手機號碼1',
        'price' => '100.00'
    ],
        [
        'mobile'=> '手機號碼2',
        'price' => '500.00'
    ],
];

一維數(shù)組的驗證是直接可以

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

但是現(xiàn)在是二維數(shù)組,Tp是有自定義驗證的,現(xiàn)在想驗證的是,數(shù)組里面的手機號碼必須有值而且必須是合法的手機號碼,金額必須為正整數(shù)或者小數(shù)點后有兩位!

自定義驗證:

  protected $rule = [
    'mobile'=> 'require|array|checkMobile',
  ]
//自定義驗證函數(shù)
protected function checkMobile()
{
  //在這里面咋使用驗證呢?
  //最好是可以使用Tp自帶的規(guī)則 比如mobile require unique等!!!!
}
回答
編輯回答
孤毒

emmm,foreach去調(diào)用抽象出來獨立的validator,一點思路,我看了之前的TP5的小項目,好像最多也是一位數(shù)組的校驗,希望對你有所幫助

2018年9月22日 16:05
編輯回答
故人嘆
//自定義驗證函數(shù)
    protected function checkMobile($value)
    {
        # 01: 首先循環(huán)當(dāng)前數(shù)據(jù)  每一項的值(value)
        # 02: 之后將該值賦給 變量mobile
        # 03: 之后使用寫驗證規(guī)則和錯誤信息
        # 04: 之后將錯誤信息給$this->message();
        # 05: 最后驗證  $this->check(驗證數(shù)據(jù),驗證規(guī)則);
        # 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;
            }
        }
    }

使用的時候:

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

數(shù)據(jù)是:

$data = [
    [
        'mobile'=> ['手機號碼1','手機號碼2'],
    ];
];
2017年12月29日 10:29