หลาย ๆ คนที่เขียน php framwork คงติดปัญหาการทำ Validator บางทีมันก็มีไม่ครบ ดังที่ใจเราต้องการ เอาล่ะครับวันนี้จะมาพูดถึงเรื่องการสร้าง Function เพิ่มเพื่อให้การ validate ตรงตามความต้องการของเรา โดยการ extend โดยมีวิธีการดังนี้ class factory ของ validate อยู่ที่นี่ครับ Illuminate\Validation\Factory ลองมาดู code extend ของตัวนี้ดูครับว่ามันทำงานยังไง
* Register a custom validator extension.
*
* @param string $rule
* @param \Closure|string $extension
* @param string $message
* @return void
*/
public function extend($rule, $extension, $message = null)
{
$this->extensions[$rule] = $extension;
if ($message) $this->fallbackMessages[snake_case($rule)] = $message;
}
จะเห็นได้ว่า มีการรับค่าพารามิเตอร์ สามตัวด้วยกันครับ* rule คือ ชื่อที่เราจะตั้งขึ้นมา
* extension จะทำงานเป็นตัวตรวจสอบเงื่อนไขว่า จริงหรือเท็จ
* message คือข้อข้อความที่ต้องการแสดง
เอาล่ะครับมาดูการเขียนและการใช้งาน
/* validate has some one between shelf_id or shelf_code */
$ValidationFactory->extend('checkSomeone', function ($attribute, $value, $paramiters) {
$shelf_id = (\Input::has('shelf_id')) ? \Input::get('shelf_id') : null;
$shelf_code = (\Input::has('shelf_code')) ? \Input::get('shelf_code') : null;
if (empty($shelf_id) && empty($shelf_code)) {
return (bool) false;
} else {
return (bool) true;
}
}, 'please put some shelf id or shelfcode');
ผมเขียน function validate ขึ้นมาเพิ่มชื่อ checkSomeone ซึ่งทำการตรวจสอบค่าภายในตามเงื่อนไขที่กำหนด หากไม่เป็นจริงจะรีเทินกับไป
การใช้งาน
$v = Validator::make($this->request->all(), [
'order_id' => 'numeric|min:1',
'sort' => 'in:desc,asc',
'shelf_id' => 'checkSomeone',
การคืนค่า
if ($v->fails()) {
$res['data']['messages_errors'] = $v->errors()->toArray();
return $this->rest->error($res, 400)->render($format);
}
ง่าย ๆเพียงเท่านี้ลองเอาไปปรับใช้กันดูครับ

0 ความคิดเห็น:
แสดงความคิดเห็น