lumen 8.0 表單驗證返回中英文

charliecen發表於2020-10-26

lumen 表單驗證

規則配置檔案rules.php

<?php

return [
    'title'     =>  'required|max:10',
    'content'   =>  'required',
    'phone'     =>  'required|regex:/^1[3-8]\d{9}$/'
];

屬性配置檔案attributes.php

<?php

return [
    'title'     =>  '標題',
    'content'   =>  '內容',
    'phone'     =>  '聯絡方式'
];

中文訊息檔案resources/lang/zh/validation.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines contain the default error messages used by
    | the validator class. Some of these rules have multiple versions such
    | as the size rules. Feel free to tweak each of these messages here.
    |
    */

    'accepted'             => ':attribute必須接受',
    'active_url'           => ':attribute必須是一個合法的 URL',
    'after'                => ':attribute 必須是 :date 之後的一個日期',
    'after_or_equal'       => ':attribute 必須是 :date 之後或相同的一個日期',
    'alpha'                => ':attribute只能包含字母',
    'alpha_dash'           => ':attribute只能包含字母、數字、中劃線或下劃線',
    'alpha_num'            => ':attribute只能包含字母和數字',
    'array'                => ':attribute必須是一個陣列',
    'before'               => ':attribute 必須是 :date 之前的一個日期',
    'before_or_equal'      => ':attribute 必須是 :date 之前或相同的一個日期',
    'between'              => [
        'numeric' => ':attribute 必須在 :min 到 :max 之間',
        'file'    => ':attribute 必須在 :min 到 :max KB 之間',
        'string'  => ':attribute 必須在 :min 到 :max 個字元之間',
        'array'   => ':attribute 必須在 :min 到 :max 項之間',
    ],
    'boolean'              => ':attribute 字元必須是 true 或 false',
    'confirmed'            => ':attribute 二次確認不匹配',
    'date'                 => ':attribute 必須是一個合法的日期',
    'date_format'          => ':attribute 與給定的格式 :format 不符合',
    'different'            => ':attribute 必須不同於 :other',
    'digits'               => ':attribute必須是 :digits 位.',
    'digits_between'       => ':attribute 必須在 :min 和 :max 位之間',
    'dimensions'           => ':attribute具有無效的圖片尺寸',
    'distinct'             => ':attribute欄位具有重複值',
    'email'                => ':attribute必須是一個合法的電子郵件地址',
    'exists'               => '選定的 :attribute 是無效的.',
    'file'                 => ':attribute必須是一個檔案',
    'filled'               => ':attribute的欄位是必填的',
    'image'                => ':attribute必須是 jpeg, png, bmp 或者 gif 格式的圖片',
    'in'                   => '選定的 :attribute 是無效的',
    'in_array'             => ':attribute 欄位不存在於 :other',
    'integer'              => ':attribute 必須是個整數',
    'ip'                   => ':attribute必須是一個合法的 IP 地址。',
    'json'                 => ':attribute必須是一個合法的 JSON 字串',
    'max'                  => [
        'numeric' => ':attribute 的最大長度為 :max 位',
        'file'    => ':attribute 的最大為 :max',
        'string'  => ':attribute 的最大長度為 :max 字元',
        'array'   => ':attribute 的最大個數為 :max 個.',
    ],
    'mimes'                => ':attribute 的檔案型別必須是 :values',
    'min'                  => [
        'numeric' => ':attribute 的最小長度為 :min 位',
        'file'    => ':attribute 大小至少為 :min KB',
        'string'  => ':attribute 的最小長度為 :min 字元',
        'array'   => ':attribute 至少有 :min 項',
    ],
    'not_in'               => '選定的 :attribute 是無效的',
    'numeric'              => ':attribute 必須是數字',
    'present'              => ':attribute 欄位必須存在',
    'regex'                => ':attribute 格式是無效的',
    'required'             => ':attribute 欄位是必須的',
    'required_if'          => ':attribute 欄位是必須的當 :other 是 :value',
    'required_unless'      => ':attribute 欄位是必須的,除非 :other 是在 :values 中',
    'required_with'        => ':attribute 欄位是必須的當 :values 是存在的',
    'required_with_all'    => ':attribute 欄位是必須的當 :values 是存在的',
    'required_without'     => ':attribute 欄位是必須的當 :values 是不存在的',
    'required_without_all' => ':attribute 欄位是必須的當 沒有一個 :values 是存在的',
    'same'                 => ':attribute和:other必須匹配',
    'size'                 => [
        'numeric' => ':attribute 必須是 :size 位',
        'file'    => ':attribute 必須是 :size KB',
        'string'  => ':attribute 必須是 :size 個字元',
        'array'   => ':attribute 必須包括 :size 項',
    ],
    'string'               => ':attribute 必須是一個字串',
    'timezone'             => ':attribute 必須是個有效的時區.',
    'unique'               => ':attribute 已存在',
    'url'                  => ':attribute 無效的格式',
    'mobile'               => ':attribute 手機號碼無效',

    /*
    |--------------------------------------------------------------------------
    | Custom Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | Here you may specify custom validation messages for attributes using the
    | convention "attribute.rule" to name the lines. This makes it quick to
    | specify a specific custom language line for a given attribute rule.
    |
    */

    'custom' => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Custom Validation Attributes
    |--------------------------------------------------------------------------
    |
    | The following language lines are used to swap attribute place-holders
    | with something more reader friendly such as E-Mail Address instead
    | of "email". This simply helps us make messages a little cleaner.
    |
    */

    'attributes' => [],

];

公用驗證方法

 /**
     * 檢測表單
     *
     * @param $args 必須引數
     * @param $data 表單請求引數
     * @return mixed|void
     */
    protected function checkRequest($args, $data)
    {
        $rules = $attributes = $message = [];
        foreach($args as $k){
            $rules[$k] = config('rules')[$k];
            // if (env('APP_LOCALE') == 'zh')
            if (Cache::get('lan_'. Auth::id()) == 'zh')
                $attributes[$k] = config('attributes')[$k];
        }
        $validator = Validator::make($data, $rules, $message, $attributes);
        if ($validator->fails()) {
            foreach($validator->errors()->getMessages() as $error) {
                return $error[0];
            }
        }
        return;
    }

控制器方法

public function store_with_mq(Request $request)
{
    // 驗證引數
    $args = ['title', 'content', 'phone'];
    $data = $request->only($args);
    $error = $this->checkRequest($args, $data);
    if (!empty($error)) return resp(Code::Failed, $error);
}

切換語言方法

public function changeLocale(Request $request)
{
    if ($request->has('lan')){
        $lan = $request->get('lan');
        if (in_array($lan, ['en','zh'])) {
            Cache::put('lan_' . Auth::id(), $lan);
        }
        return resp(Code::Success, Msg::Success);
    }
    return resp(Code::Failed, Msg::Failed);
}

切換語言中介軟體

注意,這裡需要在bootstrap/app.php裡新增路由中介軟體

 $app->routeMiddleware([
     'SwitchLan'    =>  \App\Http\Middleware\ChangeLanguage::class,
 ]);

具體程式碼如下:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;

class ChangeLanguage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($user = auth()->user()) {
            $key = 'lan_' . $user->id;
            if (Cache::has($key) && in_array(Cache::get($key), ['en', 'zh'])) {
                App::setLocale(Cache::get($key));
            } else {
                App::setLocale('zh');
            }
        } else {
            App::setLocale('zh');
        }
        return $next($request);
    }
}

定義路由

$router->group([
  'prefix' => 'api',
  'namespace' => 'Api',
  'middleware' => ['auth:api', 'SwitchLan']
], function () use ($router) {
    $router->get('/changeLocale', 'UserController@changeLocale');
    $router->post('/posts', 'PostsController@store_with_mq');
    $router->get('/posts', 'PostsController@index');
});

測試postman


curl --location --request POST 'localhost:84/api/posts' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODRcL2F1dGhcL2xvZ2luIiwiaWF0IjoxNjAzNzY1MzUxLCJleHAiOjE2MDM3Njg5NTEsIm5iZiI6MTYwMzc2NTM1MSwianRpIjoiN2Y2Y1B5eDVNRlpnNUQ5RCIsInN1YiI6MSwicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9._6zoL2buRS6-y9c13xPSZGEy2cHEEoFRg1x0GxjMvg0' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: laravel_session=go3wRgLpOKusZYLYz2ik27H1ZSjk0E5VxBYLliOI' \
--data-urlencode 'title=43433566' \
--data-urlencode 'content=1112' \
--data-urlencode 'phone=132212219090'
{
    "code": 500,
    "msg": "聯絡方式 格式是無效的",
    "data": []
}

curl --location --request POST 'localhost:84/api/posts' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODRcL2F1dGhcL2xvZ2luIiwiaWF0IjoxNjAzNzY1MzUxLCJleHAiOjE2MDM3Njg5NTEsIm5iZiI6MTYwMzc2NTM1MSwianRpIjoiN2Y2Y1B5eDVNRlpnNUQ5RCIsInN1YiI6MSwicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9._6zoL2buRS6-y9c13xPSZGEy2cHEEoFRg1x0GxjMvg0' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: laravel_session=go3wRgLpOKusZYLYz2ik27H1ZSjk0E5VxBYLliOI' \
--data-urlencode 'title=4343356612131' \
--data-urlencode 'content=1112' \
--data-urlencode 'phone=132212219090'
{
    "code": 500,
    "msg": "標題 的最大長度為 10 字元",
    "data": []
}

切換英文

curl --location --request GET 'localhost:84/api/changeLocale?lan=en' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODRcL2F1dGhcL2xvZ2luIiwiaWF0IjoxNjAzNzY1MzUxLCJleHAiOjE2MDM3Njg5NTEsIm5iZiI6MTYwMzc2NTM1MSwianRpIjoiN2Y2Y1B5eDVNRlpnNUQ5RCIsInN1YiI6MSwicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9._6zoL2buRS6-y9c13xPSZGEy2cHEEoFRg1x0GxjMvg0' \
--header 'Cookie: laravel_session=go3wRgLpOKusZYLYz2ik27H1ZSjk0E5VxBYLliOI'

{
    "code": 200,
    "msg": "成功",
    "data": []
}

測試

{
    "code": 500,
    "msg": "The title may not be greater than 10 characters.",
    "data": []
}

{
    "code": 500,
    "msg": "The phone format is invalid.",
    "data": []
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章