laravel 定义表单form验证类

<?php

namespace App\Http\Requests;

use App\Exceptions\BaseException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class OrderRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'coin_type' => 'required',
'coin_num' => 'required|integer|numeric',
];
}
public function messages()
{
return [
'coin_type.required' => '硬币类型必填',
'coin_num.required' => '硬币数量必填',
'coin_num.numeric' => '硬币不可以是字符串',
'coin_num.integer' => '硬币必须是整数',
];
}
protected function failedValidation(Validator $validator)
{
throw new BaseException($validator->errors()->first());
}

}

可以基础api
<?php

namespace App\Http\Requests;

use App\Exceptions\BaseException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class BaseRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * @author maxubin
     * @return array
     */
    public function rules()
    {
        $verifyMethod = \Route::current() ? \Route::current()->getActionMethod() : '';
        if(! method_exists($this, $verifyMethod)) {
            return [];
        }
        return $this->{$verifyMethod}();
    }

    /**
     * @author maxubin
     * @param Validator $validator
     * @throws Exception
     */
    protected function failedValidation(Validator $validator)
    {
        throw new BaseException($validator->errors()->first());
    }
}

  

posted @ 2022-07-18 17:14  星云惊蛰  阅读(46)  评论(0)    收藏  举报