iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 13
1

如何確認 request body的參數是符合我們預期的?
除了透過資料庫的欄位設定之外,Laravel有個 ValidatesRequests trait 提供眾多驗證機制來避免寫入錯誤的資料。

基本作法

方法1 Validator::make

$validator = Validator::make($request->all(), [
            'user_id' => 'required',
            'content' => 'required'
]);

if ($validator->fails()) {
    $messages = $validator->errors()->all();
    $msg = $messages[0];
    return response()->json(['success_code' => 401, 'response_code' => 0, 'response_message' => $msg]);
}

方法2 $request->validate($rules, $message);

記得要先有 use Illuminate\Validation\ValidationException;

try {
     $rules = [ "user_id" => "required|integer","content" => "required|string" ];
     $message = [ "user_id.required" => "請輸入id","content.required" => "請輸入文章內容" ];
     $request->validate($rules, $message)
} catch (ValidationException $exception) {
     $errorMessage =$exception->validator->getMessageBag()->getMessages();
     return  $errorMessage;
} 

以註冊為例

public function registerAPI(Request $request)
    {
        try {
            $rules = [
                "name" => "required|string | between:1,10 ",
                "email" => "required| email | unique:users,email",
                "password" => "required|string| between:6,12 | regex:/^[A-Za-z0-9]+$/",
            ];
            $message = [   // 欄位名稱.驗證方法名稱
                "name.required" => "請輸入名稱",
                "email.required" => "請輸入email",
                "password.required" => "請輸入密碼",
                "email.email" => "email格式錯誤",
                "email.unique" => "email已使用",
                "name.between" => "name 字數需6~12",
                "password.regex" => "請勿輸入特殊符號",
            ];
            $validResult = $request->validate($rules, $message);
        } catch (ValidationException $exception) {

            $errorObject = $exception->validator->getMessageBag()->getMessages();
            $errorMessage = '';
            foreach($errorObject as $key => $value) {
                $errorMessage =  $value[0];
            }
            return response()->json(['message' => $errorMessage], 201);
        }

        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => $request->password,
        ]);

        return response()->json(['message' => 'register success , please login '], 201);
  • rules裡頭可以放各種官方文件有提到驗證機制,個人常用的如下:

    • required 必填
    • email 需要是email的格式
    • unique 不可重複在資料表內
    • regex 需符合正規表達式的規範等
  • message可針對rules設定回覆內容,沒設定系統會有預定的回覆訊息。

驗證成果

有遇到request欄位錯誤,就會產生這樣的錯誤內容。

https://ithelp.ithome.com.tw/upload/images/20200927/20125263OfTKl2lTV4.png
可提供前端顯示錯誤訊息或是後端自我檢查錯誤狀況。


參考資料
https://docs.laravel-dojo.com/laravel/5.5/validation
https://laravel.com/docs/7.x/validation
https://stackoverflow.com/questions/47219542/how-can-i-manually-return-or-throw-a-validation-error-exception-in-laravel
https://hackmd.io/@8irD0FCGSQqckvMnLpAmzw/HJ1LqggUQ?type=view
https://laracasts.com/discuss/channels/laravel/get-the-message-in-validationexception


上一篇
Eloquent ORM 實作(2):以登入為例
下一篇
Middleware (1):驗證token
系列文
30天開發與部署 Laravel 專案30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言