
もくじ
この記事の内容
PDFファイルのアップロードのバリデーションを作ってみました🐱
- 拡張子が.pdf
- 半角英数.pdfである。但し、「-」「_」は例外として許可する
Request
<?php
namespace App\Http\Requests\Team\Share;
use Illuminate\Foundation\Http\FormRequest;
use App\Rules\Team\UploadPdfRule;
class UploadEventPdfRequest extends FormRequest
{
public function __construct(
UploadPdfRule $upload_pdf_rule
) {
$this->upload_pdf_rule = $upload_pdf_rule;
}
/**
* 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 [
'pdf' => [
'required',
'file',
$this->upload_pdf_rule
]
];
}
}
ここに注目
public function rules()
{
return [
'pdf' => [
'required',
'file',
$this->upload_pdf_rule
]
];
}
- 必須である
- fileタイプ
- $this->upload_pdf_rule
App\Rules\Team\UploadPdfRuleルールを適用
Rule
<?php
namespace App\Rules\Team;
use Illuminate\Contracts\Validation\Rule;
class UploadPdfRule implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
// nullはエラー
if (is_null($value)) {
return false;
}
// 選択されたファイルの拡張子を取得する
$extension = $value->getClientOriginalExtension();
//拡張子が.pdfであることを確認
if ($extension !== "pdf") {
return false;
}
// ファイル名が「{半角英数}.pdf」であることを確認。但し「-」「_」は許可
if (!preg_match('/^[-_a-zA-Z0-9]+\.pdf$/', $value->getClientOriginalName())) {
return false;
}
return true;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return __('validation.regex');
}
}
passes()メソッド内でtrueを返さない時にバリデーションエラーになる
こういったバリデーションを柔軟に設定できるのがRuleの魅力ですね。
皆さんもオリジナルなバリデーションを作ってみてください。

