Readouble

Laravel 8.x バリデーション

イントロダクションIntroduction

Laravelは、アプリケーションの受信データをバリデーションするために複数の異なるアプローチを提供します。すべての受信HTTPリクエストで使用可能なvalidateメソッドを使用するのがもっとも一般的です。しかし、バリデーションに対する他のアプローチについても説明します。Laravel provides several different approaches to validate your application's incoming data. It is most common to use the validate method available on all incoming HTTP requests. However, we will discuss other approaches to validation as well.

Laravelは、データに適用できる便利で数多くのバリデーションルールを持っており、特定のデータベーステーブルで値が一意であるかどうかをバリデーションする機能も提供します。Laravelのすべてのバリデーション機能に精通できるように、各バリデーションルールを詳しく説明します。Laravel includes a wide variety of convenient validation rules that you may apply to data, even providing the ability to validate if values are unique in a given database table. We'll cover each of these validation rules in detail so that you are familiar with all of Laravel's validation features.

クイックスタートValidation Quickstart

Laravelの強力なバリデーション機能について学ぶため、フォームをバリデーションし、エラーメッセージをユーザーに表示する完全な例を見てみましょう。この高レベルの概要を読むことで、Laravelを使用して受信リクエストデータをバリデーションする一般的な方法を理解できます。To learn about Laravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user. By reading this high-level overview, you'll be able to gain a good general understanding of how to validate incoming request data using Laravel:

ルート定義Defining The Routes

まず、routes/web.phpファイルに以下のルートを定義してあるとしましょう。First, let's assume we have the following routes defined in our routes/web.php file:

use App\Http\Controllers\PostController;

Route::get('/post/create', [PostController::class, 'create']);
Route::post('/post', [PostController::class, 'store']);

GETのルートは新しいブログポストを作成するフォームをユーザーへ表示し、POSTルートで新しいブログポストをデータベースへ保存します。The GET route will display a form for the user to create a new blog post, while the POST route will store the new blog post in the database.

コントローラ作成Creating The Controller

次に、これらのルートへの受信リクエストを処理する単純なコントローラを見てみましょう。今のところ、storeメソッドは空のままにしておきます。Next, let's take a look at a simple controller that handles incoming requests to these routes. We'll leave the store method empty for now:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * 新ブログポスト作成フォームの表示
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * 新しいブログポストの保存
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // ブログポストのバリデーションと保存コード…
    }
}

バリデーションロジックWriting The Validation Logic

これで、新しいブログ投稿をバリデーションするロジックをstoreメソッドに入力する準備が整いました。これを行うには、Illuminate\Http\Requestオブジェクトによって提供されるvalidateメソッドを使用します。バリデーションルールにパスすると、コードは正常に実行され続けます。しかし、バリデーションに失敗するとIlluminate\Validation\ValidationException例外が投げられ、適切なエラーレスポンスが自動的にユーザーに返送されます。Now we are ready to fill in our store method with the logic to validate the new blog post. To do this, we will use the validate method provided by the Illuminate\Http\Request object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an Illuminate\Validation\ValidationException exception will be thrown and the proper error response will automatically be sent back to the user.

伝統的なHTTPリクエスト処理中にバリデーションが失敗した場合、直前のURLへのリダイレクトレスポンスが生成されます。受信リクエストがXHRリクエストの場合、バリデーションエラーメッセージを含むJSONレスポンスが返されます。If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages will be returned.

validateメソッドをもっとよく理解するため、storeメソッドに取り掛かりましょう。To get a better understanding of the validate method, let's jump back into the store method:

/**
 * 新ブログポストの保存
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // ブログポストは有効
}

ご覧のとおり、バリデーションルールはvalidateメソッドへ渡されます。心配いりません。利用可能なすべてのバリデーションルールは文書化されています。この場合でもバリデーションが失敗したとき、適切な応答が自動的に生成されます。バリデーションにパスすると、コントローラは正常に実行を継続します。As you can see, the validation rules are passed into the validate method. Don't worry - all available validation rules are documented[#available-validation-rules]. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.

もしくは、バリデーションルールを|で区切られた一つの文字列の代わりに、ルールの配列で指定することもできます。Alternatively, validation rules may be specified as arrays of rules instead of a single | delimited string:

$validatedData = $request->validate([
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
]);

さらに、validateWithBagメソッドを使用して、リクエストをバリデーションした結果のエラーメッセージをnamederrorbag内へ保存できます。In addition, you may use the validateWithBag method to validate a request and store any error messages within a named error bag[#named-error-bags]:

$validatedData = $request->validateWithBag('post', [
    'title' => ['required', 'unique:posts', 'max:255'],
    'body' => ['required'],
]);

最初のバリデーション失敗時に停止Stopping On First Validation Failure

最初のバリデーションに失敗したら、残りのバリデーションルールの判定を停止したいことも、ときどきあります。このためには、bailルールを使ってください。Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

$request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

この例の場合、title属性のuniqueルールに失敗すると、maxルールはチェックされません。ルールは指定した順番にバリデートされます。In this example, if the unique rule on the title attribute fails, the max rule will not be checked. Rules will be validated in the order they are assigned.

ネストした属性の注意点A Note On Nested Attributes

受信HTTPリクエストに「ネストされた」フィールドデータが含まれている場合は、「ドット」構文を使用してバリデーションルールでこうしたフィールドを指定できます。If the incoming HTTP request contains "nested" field data, you may specify these fields in your validation rules using "dot" syntax:

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

フィールド名にピリオドそのものが含まれている場合は、そのピリオドをバックスラッシュでエスケープし、「ドット」構文として解釈されることを明示的に防げます。On the other hand, if your field name contains a literal period, you can explicitly prevent this from being interpreted as "dot" syntax by escaping the period with a backslash:

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'v1\.0' => 'required',
]);

バリデーションエラー表示Displaying The Validation Errors

では、受信リクエストフィールドが指定したバリデーションルールにパスしない場合はどうなるでしょうか。前述のように、Laravelはユーザーを直前の場所へ自動的にリダイレクトします。さらに、すべてのバリデーションエラーとリクエスト入力は自動的にセッションに一時保持保存されます。So, what if the incoming request fields do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and request input[/docs/{{version}}/requests#retrieving-old-input] will automatically be flashed to the session[/docs/{{version}}/session#flash-data].

$errors変数は、webミドルウェアグループが提供するIlluminate\View\Middleware\ShareErrorsFromSessionミドルウェアにより、アプリケーションのすべてのビューで共有されます。このミドルウェアが適用されると、ビューで$errors変数は常に定義され、$errors変数が常に使用可能になり、安全・便利に使用できると想定できます。$errors変数はIlluminate\Support\MessageBagのインスタンスです。このオブジェクトの操作の詳細は、ドキュメントを確認してくださいAn $errors variable is shared with all of your application's views by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used. The $errors variable will be an instance of Illuminate\Support\MessageBag. For more information on working with this object, check out its documentation[#working-with-error-messages].

この例では、バリデーションに失敗すると、エラーメッセージをビューで表示できるように、コントローラのcreateメソッドへリダイレクトされることになります。So, in our example, the user will be redirected to our controller's create method when validation fails, allowing us to display the error messages in the view:

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Postフォームの作成 -->

エラーメッセージのカスタマイズCustomizing The Error Messages

Laravelの組み込みバリデーションルールにはそれぞれエラーメッセージがあり、アプリケーションのresources/lang/en/validation.phpファイルに登録されています。このファイル内に、各バリデーションルールの翻訳エントリがあります。アプリケーションの要求に基づいて、これらのメッセージを自由に変更できます。Laravel's built-in validation rules each has an error message that is located in your application's resources/lang/en/validation.php file. Within this file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application.

さらに、アプリケーションの言語へメッセージを翻訳するために、このファイルを別の翻訳言語ディレクトリにコピーできます。Laravelのローカリゼーションの詳細については、完全な多言語化ドキュメントをご覧ください。In addition, you may copy this file to another translation language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete localization documentation[/docs/{{version}}/localization].

XHRリクエストとバリデーションXHR Requests & Validation

この例では、従来のフォームを使用してデータをアプリケーションに送信しました。ただし、多くのアプリケーションは、JavaScriptを利用したフロントエンドからXHRリクエストを受信します。XHRリクエスト中にvalidateメソッドを使用すると、Laravelはリダイレクト応答を生成しません。代わりに、Laravelはすべてのバリデーションエラーを含むJSONレスポンスを生成します。このJSONレスポンスは、422 HTTPステータスコードとともに送信されます。In this example, we used a traditional form to send data to the application. However, many applications receive XHR requests from a JavaScript powered frontend. When using the validate method during an XHR request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

@errorディレクティブThe @error Directive

@errorBladeディレクティブを使用して、特定の属性にバリデーションエラーメッセージが存在するかどうかを簡単に判断できます。@errorディレクティブ内で、$message変数をエコーし​​てエラーメッセージを表示ができます。You may use the @error Blade[/docs/{{version}}/blade] directive to quickly determine if validation error messages exist for a given attribute. Within an @error directive, you may echo the $message variable to display the error message:

<!-- /resources/views/post/create.blade.php -->

<label for="title">Post Title</label>

<input id="title" type="text" name="title" class="@error('title') is-invalid @enderror">

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

名前付きエラーバッグを使用している場合は、エラーバッグの名前を @error ディレクティブの第2引数へ渡せます。If you are using named error bags[#named-error-bags], you may pass the name of the error bag as the second argument to the @error directive:

<input ... class="@error('title', 'post') is-invalid @enderror">

フォームの再取得Repopulating Forms

Laravelがバリデーションエラーのためにリダイレクトレスポンスを生成するとき、フレームワークは自動的にセッションへのリクエストのすべての入力を一時保持保存します。これは、直後のリクエスト時、保存しておいた入力に簡単にアクセスし、ユーザーが送信しようとしたフォームを再入力・再表示できるようにします。When Laravel generates a redirect response due to a validation error, the framework will automatically flash all of the request's input to the session[/docs/{{version}}/session#flash-data]. This is done so that you may conveniently access the input during the next request and repopulate the form that the user attempted to submit.

直前のリクエストから一時保持保存された入力を取得するには、Illuminate\Http\Requestのインスタンスでoldメソッドを呼び出します。oldメソッドは、直前に一時保持保存した入力データをsessionから取り出します。To retrieve flashed input from the previous request, invoke the old method on an instance of Illuminate\Http\Request. The old method will pull the previously flashed input data from the session[/docs/{{version}}/session]:

$title = $request->old('title');

Laravelはグローバルなoldヘルパも提供しています。Bladeテンプレート内に古い入力を表示している場合は、oldヘルパを使用してフォームを再入力・再表示する方が便利です。指定されたフィールドに古い入力が存在しない場合、nullが返されます。Laravel also provides a global old helper. If you are displaying old input within a Blade template[/docs/{{version}}/blade], it is more convenient to use the old helper to repopulate the form. If no old input exists for the given field, null will be returned:

<input type="text" name="title" value="{{ old('title') }}">

オプションフィールドに対する注意A Note On Optional Fields

LaravelはTrimStringsConvertEmptyStringsToNullミドルウェアをアプリケーションのデフォルトグローバルミドルウェアスタックに含んでいます。これらのミドルウェアはApp\Http\Kernelクラスでリストされています。このため、バリデータがnull値を無効であると判定しないように、オプションフィールドへnullableを付ける必要が頻繁に起きるでしょう。By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid. For example:

$request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
    'publish_at' => 'nullable|date',
]);

上記の例の場合、publish_atフィールドがnullか、有効な日付表現であることを指定しています。ルール定義にnullableが追加されないと、バリデータはnullを無効な日付として判定します。In this example, we are specifying that the publish_at field may be either null or a valid date representation. If the nullable modifier is not added to the rule definition, the validator would consider null an invalid date.

フォームリクエストバリデーションForm Request Validation

フォームリクエスト作成Creating Form Requests

より複雑なバリデーションシナリオの場合は、「フォームリクエスト」を作成することをお勧めします。フォームリクエストは、独自のバリデーションおよび認可ロジックをカプセル化するカスタムリクエストクラスです。フォームリクエストクラスを作成するには、make:request Artisan CLIコマンドを使用します。For more complex validation scenarios, you may wish to create a "form request". Form requests are custom request classes that encapsulate their own validation and authorization logic. To create a form request class, you may use the make:request Artisan CLI command:

php artisan make:request StorePostRequest

生成したフォームリクエストクラスは、app/Http/Requestsディレクトリに配置されます。このディレクトリが存在しない場合は、make:requestコマンドの実行時に作成されます。Laravelにより生成される各フォームリクエストには、authorizerulesの2つのメソッドがあります。The generated form request class will be placed in the app/Http/Requests directory. If this directory does not exist, it will be created when you run the make:request command. Each form request generated by Laravel has two methods: authorize and rules.

ご想像のとおり、authorizeメソッドは、現在認証されているユーザーがリクエストによって表されるアクションを実行できるかどうかを判断し、rulesメソッドはリクエスト中のデータを検証するバリデーションルールを返します。As you might have guessed, the authorize method is responsible for determining if the currently authenticated user can perform the action represented by the request, while the rules method returns the validation rules that should apply to the request's data:

/**
 * リクエストに適用するバリデーションルールを取得
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

lightbulb">Tip!! rulesメソッドの引数で必要な依存関係をタイプヒントにより指定することができます。それらはLaravelサービスコンテナを介して自動的に依存解決されます。{tip} You may type-hint any dependencies you require within the rules method's signature. They will automatically be resolved via the Laravel service container[/docs/{{version}}/container].

では、どのようにバリデーションルールを実行するのでしょうか?必要なのはコントローラのメソッドで、このリクエストをタイプヒントで指定することです。やって来たフォームリクエストはコントローラメソッドが呼び出される前にバリデーションを行います。つまり、コントローラでバリデーションロジックを取っ散らかす必要はありません。So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:

/**
 * 新しいブログ投稿を保存
 *
 * @param  \App\Http\Requests\StorePostRequest  $request
 * @return Illuminate\Http\Response
 */
public function store(StorePostRequest $request)
{
    // 送信されたリクエストは正しい

    // バリデーション済みデータの取得
    $validated = $request->validated();

    // バリデーション済み入力データの一部を取得
    $validated = $request->safe()->only(['name', 'email']);
    $validated = $request->safe()->except(['name', 'email']);
}

バリデーションが失敗した場合、リダイレクトレスポンスが生成され、ユーザーを直前の場所に送り返します。エラーもセッ​​ションに一時保持され、表示できます。リクエストがXHRリクエストの場合、バリデーションエラーのJSON表現を含む422ステータスコードのHTTPレスポンスがユーザーに返されます。If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an XHR request, an HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

フォームリクエストへのAfterフックを追加Adding After Hooks To Form Requests

フォームリクエストに"after"のバリデーションフックを追加する場合は、withValidatorメソッドを使用します。このメソッドは完全に構築されたバリデータを受け取り、バリデーションルールの実際の評価前に、メソッドのいずれでも呼び出せます。If you would like to add an "after" validation hook to a form request, you may use the withValidator method. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated:

/**
 * バリデータインスタンスの設定
 *
 * @param  \Illuminate\Validation\Validator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

最初のバリデーション失敗属性で停止Stopping On First Validation Failure Attribute

リクエストクラスにstopOnFirstFailureプロパティを追加することで、バリデーションの失敗が起きてすぐに、すべての属性のバリデーションを停止する必要があることをバリデータへ指示できます。By adding a stopOnFirstFailure property to your request class, you may inform the validator that it should stop validating all attributes once a single validation failure has occurred:

/**
 * バリデータが最初のルールの失敗で停​​止するかを指示
 *
 * @var bool
 */
protected $stopOnFirstFailure = true;

リダイレクト先のカスタマイズCustomizing The Redirect Location

前述のとおり、フォームリクエストのバリデーションに失敗した場合、ユーザーを元の場所に戻すためのリダイレクトレスポンスが生成されます。しかし、この動作は自由にカスタマイズ可能です。それには、フォームのリクエストで、$redirectプロパティを定義します。As previously discussed, a redirect response will be generated to send the user back to their previous location when form request validation fails. However, you are free to customize this behavior. To do so, define a $redirect property on your form request:

/**
 * バリデーション失敗時に、ユーザーをリダイレクトするURI
 *
 * @var string
 */
protected $redirect = '/dashboard';

または、ユーザーを名前付きルートへリダイレクトする場合は、$redirectRouteプロパティを代わりに定義します。Or, if you would like to redirect users to a named route, you may define a $redirectRoute property instead:

/**
 * バリデーション失敗時に、ユーザーをリダイレクトするルート
 *
 * @var string
 */
protected $redirectRoute = 'dashboard';

フォームリクエストの認可Authorizing Form Requests

フォームリクエストクラスには、authorizeメソッドも含まれています。このメソッド内で、認証済みユーザーが特定のリソースを更新する権限を持っているかどうかを判別できます。たとえば、ユーザーが更新しようとしているブログコメントを実際に所有しているかどうかを判断できます。ほとんどの場合、次の方法で認可ゲートとポリシーを操作します。The form request class also contains an authorize method. Within this method, you may determine if the authenticated user actually has the authority to update a given resource. For example, you may determine if a user actually owns a blog comment they are attempting to update. Most likely, you will interact with your authorization gates and policies[/docs/{{version}}/authorization] within this method:

use App\Models\Comment;

/**
 * ユーザーがこのリクエストの権限を持っているかを判断する
 *
 * @return bool
 */
public function authorize()
{
    $comment = Comment::find($this->route('comment'));

    return $comment && $this->user()->can('update', $comment);
}

全フォームリクエストはLaravelのベースリクエストクラスを拡張していますので、現在認証済みユーザーへアクセスする、userメソッドが使えます。また、上記例中のrouteメソッドの呼び出しにも、注目してください。たとえば{comment}パラメーターのような、呼び出しているルートで定義してあるURIパラメータにもアクセスできます。Since all form requests extend the base Laravel request class, we may use the user method to access the currently authenticated user. Also, note the call to the route method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the {comment} parameter in the example below:

Route::post('/comment/{comment}');

したがって、アプリケーションがルートモデル結合を利用している場合、解決されたモデルをリクエストのプロパティとしてアクセスすることで、コードをさらに簡潔にすることができます。Therefore, if your application is taking advantage of route model binding[/docs/{{version}}/routing#route-model-binding], your code may be made even more succinct by accessing the resolved model as a property of the request:

return $this->user()->can('update', $this->comment);

authorizeメソッドがfalseを返すと、403ステータスコードのHTTPレスポンスを自動的に返し、コントローラメソッドは実行しません。If the authorize method returns false, an HTTP response with a 403 status code will automatically be returned and your controller method will not execute.

アプリケーションの別の部分でリクエストの認可ロジックを処理する場合は、authorizeメソッドからtrueを返してください。If you plan to handle authorization logic for the request in another part of your application, you may simply return true from the authorize method:

/**
 * ユーザーがこのリクエストの権限を持っているか判断
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

lightbulb">Tip!! authorizeメソッドの引数で、必要な依存をタイプヒントにより指定できます。それらはLaravelのサービスコンテナにより、自動的に依存解決されます。{tip} You may type-hint any dependencies you need within the authorize method's signature. They will automatically be resolved via the Laravel service container[/docs/{{version}}/container].

エラーメッセージのカスタマイズCustomizing The Error Messages

フォームリクエストにより使用されているメッセージはmessageメソッドをオーバーライドすることによりカスタマイズできます。このメソッドから属性/ルールと対応するエラーメッセージのペアを配列で返してください。You may customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute / rule pairs and their corresponding error messages:

/**
 * 定義済みバリデーションルールのエラーメッセージ取得
 *
 * @return array
 */
public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required' => 'A message is required',
    ];
}

バリデーション属性のカスタマイズCustomizing The Validation Attributes

Laravelの組み込みバリデーションルールエラーメッセージの多くは、:attributeプレースホルダーを含んでいます。バリデーションメッセージの:attributeプレースホルダーをカスタム属性名に置き換えたい場合は、attributesメソッドをオーバーライドしてカスタム名を指定します。このメソッドは、属性と名前のペアの配列を返す必要があります。Many of Laravel's built-in validation rule error messages contain an :attribute placeholder. If you would like the :attribute placeholder of your validation message to be replaced with a custom attribute name, you may specify the custom names by overriding the attributes method. This method should return an array of attribute / name pairs:

/**
 * バリデーションエラーのカスタム属性の取得
 *
 * @return array
 */
public function attributes()
{
    return [
        'email' => 'email address',
    ];
}

検証のための入力準備Preparing Input For Validation

バリデーションルールを適用する前にリクエストからのデータを準備またはサニタイズする必要がある場合は、prepareForValidationメソッド使用します。If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the prepareForValidation method:

use Illuminate\Support\Str;

/**
 * バリーデーションのためにデータを準備
 *
 * @return void
 */
protected function prepareForValidation()
{
    $this->merge([
        'slug' => Str::slug($this->slug),
    ]);
}

バリデータの生成Manually Creating Validators

リクエストのvalidateメソッドを使用したくない場合は、Validatorファサードを使用し、バリデータインスタンスを生成する必要があります。 このファサードのmakeメソッドで、新しいバリデータインスタンスを生成します。If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade[/docs/{{version}}/facades]. The make method on the facade generates a new validator instance:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{
    /**
     * 新しいブログポストの保存
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // バリデーション済みデータの取得
        $validated = $validator->validated();

        // バリデーション済みデータの一部を取得
        $validated = $validator->safe()->only(['name', 'email']);
        $validated = $validator->safe()->except(['name', 'email']);

        // ブログポストの保存処理…
    }
}

makeメソッドの第1引数は、バリデーションを行うデータです。第2引数はそのデータに適用するバリデーションルールの配列です。The first argument passed to the make method is the data under validation. The second argument is an array of the validation rules that should be applied to the data.

リクエストのバリデーションが失敗したかどうかを判断した後、withErrorsメソッドを使用してエラーメッセージをセッションに一時保持保存できます。この方法を使用すると、リダイレクト後に$errors変数がビューと自動的に共有されるため、メッセージをユーザーへ簡単に表示できます。withErrorsメソッドは、バリデータ、MessageBag、またはPHPのarrayを引数に取ります。After determining whether the request validation failed, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. The withErrors method accepts a validator, a MessageBag, or a PHP array.

最初のバリデート失敗時に停止Stopping On First Validation Failure

stopOnFirstFailureメソッドは、バリデーションが失敗したら、すぐにすべての属性のバリデーションを停止する必要があることをバリデータへ指示します。The stopOnFirstFailure method will inform the validator that it should stop validating all attributes once a single validation failure has occurred:

if ($validator->stopOnFirstFailure()->fails()) {
    // ...
}

自動リダイレクトAutomatic Redirection

バリデータインスタンスを手動で作成するが、HTTPリクエストのvalidateメソッドによって提供される自動リダイレクトを利用したい場合は、既存のバリデータインスタンスでvalidateメソッドを呼び出すことができます。バリデーションが失敗した場合、ユーザーは自動的にリダイレクトされます。XHRリクエストの場合は、JSONレスポンスが返されます。If you would like to create a validator instance manually but still take advantage of the automatic redirection offered by the HTTP request's validate method, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an XHR request, a JSON response will be returned:

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

validateWithBagメソッドを使用しリクエストのバリデートを行った結果、失敗した場合に、エラーメッセージを名前付きエラーバッグへ保存することもできます。You may use the validateWithBag method to store the error messages in a named error bag[#named-error-bags] if validation fails:

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validateWithBag('post');

名前付きエラーバッグNamed Error Bags

1つのページに複数のフォームがある場合は、バリデーションエラーを含むMessageBagに名前を付けて、特定のフォームのエラーメッセージを取得可能にできます。これを実現するには、withErrorsの2番目の引数として名前を渡します。If you have multiple forms on a single page, you may wish to name the MessageBag containing the validation errors, allowing you to retrieve the error messages for a specific form. To achieve this, pass a name as the second argument to withErrors:

return redirect('register')->withErrors($validator, 'login');

$errors変数を使い、名前を付けたMessageBagインスタンスへアクセスできます。You may then access the named MessageBag instance from the $errors variable:

{{ $errors->login->first('email') }}

エラーメッセージのカスタマイズCustomizing The Error Messages

必要に応じて、Laravelが提供するデフォルトのエラーメッセージの代わりにバリデータインスタンスが使用するカスタムエラーメッセージを指定できます。カスタムメッセージを指定する方法はいくつかあります。まず、カスタムメッセージをvalidator::makeメソッドに3番目の引数として渡す方法です。If needed, you may provide custom error messages that a validator instance should use instead of the default error messages provided by Laravel. There are several ways to specify custom messages. First, you may pass the custom messages as the third argument to the Validator::make method:

$validator = Validator::make($input, $rules, $messages = [
    'required' => 'The :attribute field is required.',
]);

この例の、:attributeプレースホルダーは、バリデーション中のフィールドの名前に置き換えられます。バリデーションメッセージには他のプレースホルダーも利用できます。例をご覧ください。In this example, the :attribute placeholder will be replaced by the actual name of the field under validation. You may also utilize other placeholders in validation messages. For example:

$messages = [
    'same' => 'The :attribute and :other must match.',
    'size' => 'The :attribute must be exactly :size.',
    'between' => 'The :attribute value :input is not between :min - :max.',
    'in' => 'The :attribute must be one of the following types: :values',
];

特定の属性に対するカスタムメッセージ指定Specifying A Custom Message For A Given Attribute

特定の属性に対してのみカスタムエラーメッセージを指定したい場合があります。「ドット」表記を使用してこれを行うことができます。最初に属性の名前を指定し、次にルールを指定します。Sometimes you may wish to specify a custom error message only for a specific attribute. You may do so using "dot" notation. Specify the attribute's name first, followed by the rule:

$messages = [
    'email.required' => 'We need to know your email address!',
];

カスタム属性値の指定Specifying Custom Attribute Values

Laravelの組み込みエラーメッセージの多くには、バリデーション中のフィールドや属性の名前に置き換えられる:attributeプレースホルダーが含まれています。特定のフィールドでこれらのプレースホルダーを置き換える値をカスタマイズするには、カスタム属性表示名の配列を4番目の引数としてValidator::makeメソッドに渡します。Many of Laravel's built-in error messages include an :attribute placeholder that is replaced with the name of the field or attribute under validation. To customize the values used to replace these placeholders for specific fields, you may pass an array of custom attributes as the fourth argument to the Validator::make method:

$validator = Validator::make($input, $rules, $messages, [
    'email' => 'email address',
]);

バリデーション後のフックAfter Validation Hook

バリデーションが完了した後に実行するコールバックを添付することもできます。これにより、追加のバリデーションを簡単に実行し、メッセージコレクションにエラーメッセージを追加することもできます。利用するには、バリデータインスタンスでafterメソッドを呼び出します。You may also attach callbacks to be run after validation is completed. This allows you to easily perform further validation and even add more error messages to the message collection. To get started, call the after method on a validator instance:

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add(
            'field', 'Something is wrong with this field!'
        );
    }
});

if ($validator->fails()) {
    //
}

バリデーション済み入力の利用Working With Validated Input

フォームのリクエストや手動で作成したバリデータのインスタンスを使って リクエストデータをバリデーションした後に、バリデーション済みの受信リクエストデータを取得したいと思われるかもしれません。これには方法がいくつかあります。まず、フォームのリクエストやバリデータインスタンスのvalidatedメソッドを呼び出す方法です。このメソッドは、バリデーション済みデータの配列を返します。After validating incoming request data using a form request or a manually created validator instance, you may wish to retrieve the incoming request data that actually underwent validation. This can be accomplished in several ways. First, you may call the validated method on a form request or validator instance. This method returns an array of the data that was validated:

$validated = $request->validated();

$validated = $validator->validated();

他に、フォームリクエストやバリデータのインスタンスに対して、safeメソッドを呼び出すこともできます。このメソッドは、Illuminate\Support\ValidatedInputのインスタンスを返します。このオブジェクトはonlyexceptallメソッドを用意しており、バリデーション済みデータのサブセットや配列全体を取得できます。Alternatively, you may call the safe method on a form request or validator instance. This method returns an instance of Illuminate\Support\ValidatedInput. This object exposes only, except, and all methods to retrieve a subset of the validated data or the entire array of validated data:

$validated = $request->safe()->only(['name', 'email']);

$validated = $request->safe()->except(['name', 'email']);

$validated = $request->safe()->all();

さらに、Illuminate\Support\ValidatedInputインスタンスをループで配列のようにアクセスすることもできます。In addition, the Illuminate\Support\ValidatedInput instance may be iterated over and accessed like an array:

// バリデーション済みデータをループ
foreach ($request->safe() as $key => $value) {
    //
}

// バリデーション済みデータを配列としてアクセス
$validated = $request->safe();

$email = $validated['email'];

バリデーション済みデータへさらにフィールドを追加したい場合は、mergeメソッドを呼び出します。If you would like to add additional fields to the validated data, you may call the merge method:

$validated = $request->safe()->merge(['name' => 'Taylor Otwell']);

バリデーション済みデータをコレクションインスタンスとして取得したい場合は、collectメソッドを呼び出します。If you would like to retrieve the validated data as a collection[/docs/{{version}}/collections] instance, you may call the collect method:

$collection = $request->safe()->collect();

エラーメッセージの操作Working With Error Messages

Validatorインスタンスのerrorsメソッドを呼び出すと、エラーメッセージを操作する便利なメソッドを数揃えた、Illuminate\Support\MessageBagインスタンスを受け取ります。自動的に作成され、すべてのビューで使用できる$errors変数も、MessageBagクラスのインスタンスです。After calling the errors method on a Validator instance, you will receive an Illuminate\Support\MessageBag instance, which has a variety of convenient methods for working with error messages. The $errors variable that is automatically made available to all views is also an instance of the MessageBag class.

指定フィールドの最初のエラーメッセージ取得Retrieving The First Error Message For A Field

指定したフィールドの最初のエラーメッセージを取得するには、firstメソッドを使います。To retrieve the first error message for a given field, use the first method:

$errors = $validator->errors();

echo $errors->first('email');

指定フィールドの全エラーメッセージ取得Retrieving All Error Messages For A Field

指定したフィールドの全エラーメッセージを配列で取得したい場合は、getメソッドを使います。If you need to retrieve an array of all the messages for a given field, use the get method:

foreach ($errors->get('email') as $message) {
    //
}

配列形式のフィールドをバリデーションする場合は、*文字を使用し、各配列要素の全メッセージを取得できます。If you are validating an array form field, you may retrieve all of the messages for each of the array elements using the * character:

foreach ($errors->get('attachments.*') as $message) {
    //
}

全フィールドの全エラーメッセージ取得Retrieving All Error Messages For All Fields

全フィールドの全メッセージの配列を取得したい場合は、allメソッドを使います。To retrieve an array of all messages for all fields, use the all method:

foreach ($errors->all() as $message) {
    //
}

指定フィールドのメッセージ存在確認Determining If Messages Exist For A Field

hasメソッドは、指定したフィールドのエラーメッセージが存在しているかを判定するために使います。The has method may be used to determine if any error messages exist for a given field:

if ($errors->has('email')) {
    //
}

言語ファイルでのカスタムメッセージの指定Specifying Custom Messages In Language Files

Laravelの各組み込みバリデーションルールには、アプリケーションのresources/lang/en/validation.phpファイルにエラーメッセージが用意されています。このファイル内に、各バリデーションルールの翻訳エントリがあります。アプリケーションのニーズに基づいて、これらのメッセージを自由に変更または変更できます。Laravel's built-in validation rules each has an error message that is located in your application's resources/lang/en/validation.php file. Within this file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application.

さらに、このファイルを別の翻訳言語ディレクトリにコピーして、アプリケーションの言語のメッセージを翻訳できます。Laravelのローカリゼーションの詳細については、完全な多言語化ドキュメントをご覧ください。In addition, you may copy this file to another translation language directory to translate the messages for your application's language. To learn more about Laravel localization, check out the complete localization documentation[/docs/{{version}}/localization].

特定の属性のカスタムメッセージCustom Messages For Specific Attributes

アプリケーションのバリデーション言語ファイル内で、属性とルールの組み合わせを指定して、エラーメッセージをカスタマイズできます。これを行うには、カスタマイズメッセージをアプリケーションのresources/lang/xx/validation.php言語ファイルのcustom配列へ追加します。You may customize the error messages used for specified attribute and rule combinations within your application's validation language files. To do so, add your message customizations to the custom array of your application's resources/lang/xx/validation.php language file:

'custom' => [
    'email' => [
        'required' => 'We need to know your email address!',
        'max' => 'Your email address is too long!'
    ],
],

言語ファイルでの属性の指定Specifying Attributes In Language Files

Laravelの組み込みエラーメッセージの多くには、バリデーション中のフィールドまたは属性の名前に置き換えられる:attributeプレースホルダーが含まれています。バリデーションメッセージの:attribute部分をカスタム値に置き換えたい場合は、resources/lang/xx/validation.php言語ファイルのattributes配列でカスタム属性名を指定してください。Many of Laravel's built-in error messages include an :attribute placeholder that is replaced with the name of the field or attribute under validation. If you would like the :attribute portion of your validation message to be replaced with a custom value, you may specify the custom attribute name in the attributes array of your resources/lang/xx/validation.php language file:

'attributes' => [
    'email' => 'email address',
],

言語ファイルでの値の指定Specifying Values In Language Files

Laravelの組み込みバリデーションルールエラーメッセージの一部には、リクエスト属性の現在の値に置き換えられる:valueプレースホルダーが含まれています。ただし、バリデーションメッセージの:value部分を値のカスタム表現へ置き換えたい場合があるでしょう。たとえば、payment_typeの値がccの場合にクレジットカード番号が必要であることを定義する次のルールについて考えてみます。Some of Laravel's built-in validation rule error messages contain a :value placeholder that is replaced with the current value of the request attribute. However, you may occasionally need the :value portion of your validation message to be replaced with a custom representation of the value. For example, consider the following rule that specifies that a credit card number is required if the payment_type has a value of cc:

Validator::make($request->all(), [
    'credit_card_number' => 'required_if:payment_type,cc'
]);

このバリデーションルールが通らない場合に、次のようなメッセージが表示されるとします。If this validation rule fails, it will produce the following error message:

The credit card number field is required when payment type is cc.

支払いタイプの値としてccを表示する代わりに、values配列を定義することにより、resources/lang/xx/validation.php言語ファイルでよりユーザーフレンドリーな値表現が指定できます。Instead of displaying cc as the payment type value, you may specify a more user-friendly value representation in your resources/lang/xx/validation.php language file by defining a values array:

'values' => [
    'payment_type' => [
        'cc' => 'credit card'
    ],
],

この値を定義したら、バリデーションルールは次のエラーメッセージを生成します。After defining this value, the validation rule will produce the following error message:

The credit card number field is required when payment type is credit card.

使用可能なバリデーションルールAvailable Validation Rules

使用可能な全バリデーションルールとその機能の一覧です。Below is a list of all available validation rules and their function:

acceptedaccepted

フィールドが、"yes""on"1、またはtrueであることをバリデートします。これは、「利用規約」の承認または同様のフィールドをバリデーションするのに役立ちます。The field under validation must be "yes", "on", 1, or true. This is useful for validating "Terms of Service" acceptance or similar fields.

accepted_if:他のフィールド,値,...accepted_if:anotherfield,value,...

他のフィールドが指定した値と等しい場合、このフィールドは "yes""on"1trueであることをバリデートします。これは、"Terms of Service "の了承や似たようなフィールドをバリデートするのに便利です。The field under validation must be "yes", "on", 1, or true if another field under validation is equal to a specified value. This is useful for validating "Terms of Service" acceptance or similar fields.

active_urlactive_url

フィールドが、dns_get_record PHP関数により、有効なAかAAAAレコードであることをバリデートします。dns_get_recordへ渡す前に、parse_url PHP関数により指定したURLのホスト名を切り出します。The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function. The hostname of the provided URL is extracted using the parse_url PHP function before being passed to dns_get_record.

after:日付after:date

フィールドは、指定された日付以降の値であることをバリデートします。日付を有効なDateTimeインスタンスに変換するため、strtotimePHP関数に渡します。The field under validation must be a value after a given date. The dates will be passed into the strtotime PHP function in order to be converted to a valid DateTime instance:

'start_date' => 'required|date|after:tomorrow'

strtotimeにより評価される日付文字列を渡す代わりに、その日付と比較する他のフィールドを指定することもできます。Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

after_or_equal:日付after_or_equal:date

フィールドが指定した日付以降であることをバリデートします。詳細はafterルールを参照してください。The field under validation must be a value after or equal to the given date. For more information, see the after[#rule-after] rule.

alphaalpha

フィールドが全部アルファベット文字であることをバリデートします。The field under validation must be entirely alphabetic characters.

alpha_dashalpha_dash

フィールドが全部アルファベット文字と数字、ダッシュ(-)、下線(_)であることをバリデートします。The field under validation may have alpha-numeric characters, as well as dashes and underscores.

alpha_numalpha_num

フィールドが全部アルファベット文字と数字であることをバリデートします。The field under validation must be entirely alpha-numeric characters.

arrayarray

フィールドがPHPの配列タイプであることをバリデートします。The field under validation must be a PHP array.

arrayルールに追加の値を指定する場合、入力配列の各キーは、ルールに指定した値のリスト内に存在する必要があります。次の例では、入力配列のadminキーは、arrayルールにした値のリストに含まれていないので、無効です。When additional values are provided to the array rule, each key in the input array must be present within the list of values provided to the rule. In the following example, the admin key in the input array is invalid since it is not contained in the list of values provided to the array rule:

use Illuminate\Support\Facades\Validator;

$input = [
    'user' => [
        'name' => 'Taylor Otwell',
        'username' => 'taylorotwell',
        'admin' => true,
    ],
];

Validator::make($input, [
    'user' => 'array:username,locale',
]);

一般的に、配列内に存在することが許される配列キーを常に指定する必要があります。そうしないと、バリデータのvalidatevalidatedメソッドは他のネストした配列バリデーションルールにより検証されていなくても、配列とそのすべてのキーを含むバリデーション済みデータをすべて返してしまうことになります。In general, you should always specify the array keys that are allowed to be present within your array. Otherwise, the validator's validate and validated methods will return all of the validated data, including the array and all of its keys, even if those keys were not validated by other nested array validation rules.

必要に応じ、許可するキーのリストを指定せずにarrayルールを使用した場合でも、Laravelのバリデータが返す「検証済み」データに未検証の配列キーを含めないように指示できます。そうするには、アプリケーションのAppServiceProviderbootメソッドでバリデータのexcludeUnvalidatedArrayKeysメソッドを呼び出してください。それによりバリデータは、ネストする配列ルールにより検証された場合にのみ返される「検証済み」データへ配列キーを含めます。If you would like, you may instruct Laravel's validator to never include unvalidated array keys in the "validated" data it returns, even if you use the array rule without specifying a list of allowed keys. To accomplish this, you may call the validator's excludeUnvalidatedArrayKeys method in the boot method of your application's AppServiceProvider. After doing so, the validator will include array keys in the "validated" data it returns only when those keys were specifically validated by nested array rules[#validating-arrays]:

use Illuminate\Support\Facades\Validator;

/**
 * 全アプリケーションサービスの登録
 *
 * @return void
 */
public function boot()
{
    Validator::excludeUnvalidatedArrayKeys();
}

bailbail

フィールドでバリデーションにはじめて失敗した時点で、残りのルールのバリデーションを中止します。Stop running validation rules for the field after the first validation failure.

bailルールはバリデーションが失敗したときに、特定のフィールドのバリデーションのみを停止するだけで、一方のstopOnFirstFailureメソッドは、ひとつバリデーション失敗が発生したら、すべての属性のバリデーションを停止する必要があることをバリデータに指示します。While the bail rule will only stop validating a specific field when it encounters a validation failure, the stopOnFirstFailure method will inform the validator that it should stop validating all attributes once a single validation failure has occurred:

if ($validator->stopOnFirstFailure()->fails()) {
    // ...
}

before:日付before:date

フィールドは、指定された日付より前の値であることをバリデートします。日付を有効なDateTimeインスタンスへ変換するために、PHPのstrtotime関数へ渡します。さらに、afterルールと同様に、バリデーション中の別のフィールドの名前をdateの値として指定できます。The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function in order to be converted into a valid DateTime instance. In addition, like the after[#rule-after] rule, the name of another field under validation may be supplied as the value of date.

before_or_equal:日付before_or_equal:date

フィールドは、指定された日付より前または同じ値であることをバリデートします。日付を有効なDateTimeインスタンスへ変換するために、PHPのstrtotime関数へ渡します。さらに、afterルールと同様に、バリデーション中の別のフィールドの名前をdateの値として指定できます。The field under validation must be a value preceding or equal to the given date. The dates will be passed into the PHP strtotime function in order to be converted into a valid DateTime instance. In addition, like the after[#rule-after] rule, the name of another field under validation may be supplied as the value of date.

between:min,maxbetween:min,max

フィールドが指定された最小値最大値の間のサイズであることをバリデートします。sizeルールと同様の判定方法で、文字列、数値、配列、ファイルが評価されます。The field under validation must have a size between the given min and max. Strings, numerics, arrays, and files are evaluated in the same fashion as the size[#rule-size] rule.

booleanboolean

フィールドが論理値として有効であることをバリデートします。受け入れられる入力は、truefalse10"1""0"です。The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".

confirmedconfirmed

フィールドが、{field}_confirmationフィールドと一致する必要があります。たとえば、バリデーション中のフィールドが「password」の場合、「password_confirmation」フィールドが入力に存在し一致している必要があります。The field under validation must have a matching field of {field}_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

current_passwordcurrent_password

フィールドが、認証されているユーザーのパスワードと一致することをバリデートします。ルールの最初のパラメータで、認証ガードを指定できます。The field under validation must match the authenticated user's password. You may specify an authentication guard[/docs/{{version}}/authentication] using the rule's first parameter:

'password' => 'current_password:api'

datedate

パリデーションされる値はPHP関数のstrtotimeにより、有効で相対日付ではないことをバリデートします。The field under validation must be a valid, non-relative date according to the strtotime PHP function.

date_equals:日付date_equals:date

フィールドが、指定した日付と同じことをバリデートします。日付を有効なDateTimeインスタンスに変換するために、PHPのstrtotime関数へ渡します。The field under validation must be equal to the given date. The dates will be passed into the PHP strtotime function in order to be converted into a valid DateTime instance.

date_format:フォーマットdate_format:format

バリデーションされる値がフォーマット定義と一致するか確認します。バリデーション時にはdatedate_formatどちらかを使用しなくてはならず、両方はできません。このバリデーションはPHPのDateTimeクラスがサポートするフォーマットをすべてサポートしています。The field under validation must match the given format. You should use either date or date_format when validating a field, not both. This validation rule supports all formats supported by PHP's DateTime[https://www.php.net/manual/en/class.datetime.php] class.

declineddeclined

フィールドが"no""off"0falseであることをバリデートします。The field under validation must be "no", "off", 0, or false.

declined_if:他のフィールド,値,...declined_if:anotherfield,value,...

他のフィールドが指定した値と等しい場合、このフィールドは"no", "off", 0, or falseであることをバリデートします。The field under validation must be "no", "off", 0, or false if another field under validation is equal to a specified value.

different:フィールドdifferent:field

フィールドが指定されたフィールドと異なった値を指定されていることをバリデートします。The field under validation must have a different value than field.

digits:digits:value

フィールドが数値で、の桁数であることをバリデートします。The field under validation must be numeric and must have an exact length of value.

digits_between:最小値,最大値digits_between:min,max

フィールドが整数で、桁数が最小値から最大値の間であることをバリデートします。The field under validation must be numeric and must have a length between the given min and max.

dimensionsdimensions

バリデーション対象のファイルが、パラメータにより指定されたサイズに合致することをバリデートします。The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters:

'avatar' => 'dimensions:min_width=100,min_height=200'

使用可能なパラメータは、min_widthmax_widthmin_heightmax_heightwidth__heightratioです。Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.

**ratio**制約は、幅を高さで割ったものとして表す必要があります。これは、3/2のような分数または1.5のようなfloatのいずれかで指定します。A ratio constraint should be represented as width divided by height. This can be specified either by a fraction like 3/2 or a float like 1.5:

'avatar' => 'dimensions:ratio=3/2'

このルールは多くの引数を要求するので、Rule::dimensionsメソッドを使い、記述的にこのルールを構築してください。Since this rule requires several arguments, you may use the Rule::dimensions method to fluently construct the rule:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->maxHeight(500)->ratio(3 / 2),
    ],
]);

distinctdistinct

配列のバリデーション時、フィールドに重複した値がないことをバリデートします。When validating arrays, the field under validation must not have any duplicate values:

'foo.*.id' => 'distinct'

distinctはデフォルトで緩い比較を使用します。厳密な比較を使用するには、検証ルール定義にstrictパラメータを追加することができます。Distinct uses loose variable comparisons by default. To use strict comparisons, you may add the strict parameter to your validation rule definition:

'foo.*.id' => 'distinct:strict'

バリデーションルールの引数にignore_caseを追加して、大文字と小文字の違いを無視するルールを加えられます。You may add ignore_case to the validation rule's arguments to make the rule ignore capitalization differences:

'foo.*.id' => 'distinct:ignore_case'

emailemail

バリデーション中のフィールドは、電子メールアドレスのフォーマットである必要があります。このバリデーションルールは、egulias/email-validatorパッケージを使用して電子メールアドレスをバリデーションします。デフォルトではRFCValidationバリデータが適用されますが、他のバリデーションスタイルを適用することもできます。The field under validation must be formatted as an email address. This validation rule utilizes the egulias/email-validator[https://github.com/egulias/EmailValidator] package for validating the email address. By default, the RFCValidation validator is applied, but you can apply other validation styles as well:

'email' => 'email:rfc,dns'

上記の例では、RFCValidationDNSCheckValidationバリデーションを適用しています。適用可能なバリデーションスタイルは、次の通りです。The example above will apply the RFCValidation and DNSCheckValidation validations. Here's a full list of validation styles you can apply:

  • rfc: RFCValidationrfc: RFCValidation
  • strict: NoRFCWarningsValidationstrict: NoRFCWarningsValidation
  • dns: DNSCheckValidationdns: DNSCheckValidation
  • spoof: SpoofCheckValidationspoof: SpoofCheckValidation
  • filter: FilterEmailValidationfilter: FilterEmailValidation

PHPのfilter_var関数を使用するfilterバリデータは、Laravelに付属しており、Laravelバージョン5.8より前のLaravelのデフォルトの電子メールバリデーション動作でした。The filter validator, which uses PHP's filter_var function, ships with Laravel and was Laravel's default email validation behavior prior to Laravel version 5.8.

Note: note dnsおよびspoofバリデータには、PHPのintl拡張が必要です。{note} The dns and spoof validators require the PHP intl extension.

ends_with:foo,bar,...ends_with:foo,bar,...

フィールドの値が、指定された値で終わることをバリデートします。The field under validation must end with one of the given values.

enumenum

Enumルールはクラスベースのルールで、対象のフィールドに有効なenumの値が含まれているかどうかをバリデートします。Enumルールは、コンストラクタの引数に唯一、enumの名前を取ります。The Enum rule is a class based rule that validates whether the field under validation contains a valid enum value. The Enum rule accepts the name of the enum as its only constructor argument:

use App\Enums\ServerStatus;
use Illuminate\Validation\Rules\Enum;

$request->validate([
    'status' => [new Enum(ServerStatus::class)],
]);

Note: note Enumは、PHPバージョン8.1以上でのみ使用可能です。{note} Enums are only available on PHP 8.1 .

excludeexclude

フィルードの値がvalidatevalidatedメソッドが返すリクエストデータから除外されていることをバリデートします。The field under validation will be excluded from the request data returned by the validate and validated methods.

exclude_if:他のフィールド,exclude_if:anotherfield,value

他のフィールドと等しい場合、validatevalidatedメソッドが返すリクエストデータから、バリデーション指定下のフィールドが除外されます。The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is equal to value.

exclude_unless:他のフィールド,exclude_unless:anotherfield,value

他のフィールドと等しくない場合、validatevalidatedメソッドが返すリクエストデータから、バリデーション指定下のフィールドが除外されます。もしnullexclude_unless:name,null)の場合は、比較フィールドがnullであるか、比較フィールドがリクエストデータに含まれていない限り、バリデーション指定下のフィールドは除外されます。The field under validation will be excluded from the request data returned by the validate and validated methods unless anotherfield's field is equal to value. If value is null (exclude_unless:name,null), the field under validation will be excluded unless the comparison field is null or the comparison field is missing from the request data.

exclude_without:他のフィールドexclude_without:anotherfield

他のフィールドが存在しない場合、validatevalidatedメソッドが返すリクエストデータから、バリデーション指定下のフィールドが除外されます。The field under validation will be excluded from the request data returned by the validate and validated methods if the anotherfield field is not present.

exists:テーブル,カラムexists:table,column

フィールドは、指定のデータベーステーブルに存在する必要があります。The field under validation must exist in a given database table.

基本的なExistsルールの使用法Basic Usage Of Exists Rule

'state' => 'exists:states'

columnオプションが指定されていない場合、フィールド名が使用されます。したがって、この場合、ルールは、statesデータベーステーブルに、リクエストのstate属性値と一致するstateカラム値を持つレコードが含まれていることをバリデーションします。If the column option is not specified, the field name will be used. So, in this case, the rule will validate that the states database table contains a record with a state column value matching the request's state attribute value.

カスタムカラム名の指定Specifying A Custom Column Name

データベーステーブル名の後に配置することで、バリデーションルールで使用するデータベースカラム名を明示的に指定できます。You may explicitly specify the database column name that should be used by the validation rule by placing it after the database table name:

'state' => 'exists:states,abbreviation'

場合によっては、existsクエリに使用する特定のデータベース接続を指定する必要があります。これは、接続名をテーブル名の前に付けることで実現できます。Occasionally, you may need to specify a specific database connection to be used for the exists query. You can accomplish this by prepending the connection name to the table name:

'email' => 'exists:connection.staff,email'

テーブル名を直接指定する代わりに、Eloquentモデルを指定することもできます。Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:

'user_id' => 'exists:App\Models\User,id'

バリデーションルールで実行されるクエリをカスタマイズしたい場合は、ルールをスラスラと定義できるRuleクラスを使ってください。下の例では、|文字を区切りとして使用する代わりに、バリデーションルールを配列として指定しています。If you would like to customize the query executed by the validation rule, you may use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit them:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::exists('staff')->where(function ($query) {
            return $query->where('account_id', 1);
        }),
    ],
]);

filefile

フィールドがアップロードに成功したファイルであることをバリデートします。The field under validation must be a successfully uploaded file.

filledfilled

フィールドが存在する場合、空でないことをバリデートします。The field under validation must not be empty when it is present.

gt:fieldgt:field

フィールドが指定したフィールドより大きいことをバリデートします。2つのフィールドは同じタイプでなくてはなりません。文字列、数値、配列、ファイルは、sizeルールと同じ規約により評価します。The field under validation must be greater than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size[#rule-size] rule.

gte:fieldgte:field

フィールドが指定したフィールド以上であることをバリデートします。2つのフィールドは同じタイプでなくてはなりません。文字列、数値、配列、ファイルは、sizeルールと同じ規約により評価します。The field under validation must be greater than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size[#rule-size] rule.

imageimage

ファイルは画像(jpg、jpeg、png、bmp、gif、svg、webp)である必要があります。The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp).

in:foo,bar...in:foo,bar,...

フィールドが指定したリストの中の値に含まれていることをバリデートします。このルールを使用するために配列をimplodeする必要が多くなりますので、ルールを記述的に構築するには、Rule::inメソッドを使ってください。The field under validation must be included in the given list of values. Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
]);

inルールとarrayルールを組み合わせた場合、入力配列の各値は、inルールに指定した値のリスト内に存在しなければなりません。次の例では,入力配列中のLAS空港コードは,inルールへ指定した空港のリストに含まれていないため無効です。When the in rule is combined with the array rule, each value in the input array must be present within the list of values provided to the in rule. In the following example, the LAS airport code in the input array is invalid since it is not contained in the list of airports provided to the in rule:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

$input = [
    'airports' => ['NYC', 'LAS'],
];

Validator::make($input, [
    'airports' => [
        'required',
        'array',
        Rule::in(['NYC', 'LIT']),
    ],
]);

in_array:他のフィールド.*in_array:anotherfield.*

フィールドが、他のフィールドの値のどれかであることをバリデートします。The field under validation must exist in anotherfield's values.

integerinteger

フィールドが整数値であることをバリデートします。The field under validation must be an integer.

Note: note このバリデーションルールは、入力が「整数」変数タイプであるか確認しません。入力がPHPのFILTER_VALIDATE_INTルールで受け入れられるか検証するだけです。入力を数値として検証する必要がある場合は、このルールをnumericバリデーションルールと組み合わせて使用​​してください。{note} This validation rule does not verify that the input is of the "integer" variable type, only that the input is of a type accepted by PHP's FILTER_VALIDATE_INT rule. If you need to validate the input as being a number please use this rule in combination with the numeric validation rule[#rule-numeric].

ipip

フィールドがIPアドレスの形式として正しいことをバリデートします。The field under validation must be an IP address.

ipv4ipv4

フィールドがIPv4アドレスの形式として正しいことをバリデートします。The field under validation must be an IPv4 address.

ipv6ipv6

フィールドがIPv6アドレスの形式として正しいことをバリデートします。The field under validation must be an IPv6 address.

mac_addressmac_address

フィールドがMACアドレスとして正しいことをバリデートします。The field under validation must be a MAC address.

jsonjson

フィールドが有効なJSON文字列であることをバリデートします。The field under validation must be a valid JSON string.

lt:fieldlt:field

フィールドが指定したフィールドより小さいことをバリデートします。2つのフィールドは同じタイプでなくてはなりません。文字列、数値、配列、ファイルは、sizeルールと同じ規約により評価します。The field under validation must be less than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size[#rule-size] rule.

lte:fieldlte:field

フィールドが指定したフィールド以下であることをバリデートします。2つのフィールドは同じタイプでなくてはなりません。文字列、数値、配列、ファイルは、sizeルールと同じ規約により評価します。The field under validation must be less than or equal to the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size[#rule-size] rule.

max:max:value

フィールドが最大値として指定された以下であることをバリデートします。sizeルールと同様の判定方法で、文字列、数値、配列、ファイルが評価されます。The field under validation must be less than or equal to a maximum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size[#rule-size] rule.

mimetypes:text/plain,...mimetypes:text/plain,...

フィールドが指定されたMIMEタイプのどれかであることをバリデートします。The file under validation must match one of the given MIME types:

'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

アップロードしたファイルのMIMEタイプを判別するために、ファイルの内容が読み取られ、フレームワークはMIMEタイプを推測します。これは、クライアントが提供するMIMEタイプとは異なる場合があります。To determine the MIME type of the uploaded file, the file's contents will be read and the framework will attempt to guess the MIME type, which may be different from the client's provided MIME type.

mimes:foo,bar,...mimes:foo,bar,...

フィールドで指定されたファイルが拡張子のリストの中のMIMEタイプのどれかと一致することをバリデートします。The file under validation must have a MIME type corresponding to one of the listed extensions.

MIMEルールの基本的な使用法Basic Usage Of MIME Rule

'photo' => 'mimes:jpg,bmp,png'

拡張子を指定するだけでもよいのですが、このルールは実際には、ファイルの内容を読み取ってそのMIMEタイプを推測することにより、ファイルのMIMEタイプをバリデーションします。MIMEタイプとそれに対応する拡張子の完全なリストは、次の場所にあります。Even though you only need to specify the extensions, this rule actually validates the MIME type of the file by reading the file's contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may be found at the following location:

https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:min:value

フィールドが最小値として指定された以上であることをバリデートします。sizeルールと同様の判定方法で、文字列、数値、配列、ファイルが評価されます。The field under validation must have a minimum value. Strings, numerics, arrays, and files are evaluated in the same fashion as the size[#rule-size] rule.

multiple_of:multiple_of:value

フィールドが、の倍数であることをバリデートします。The field under validation must be a multiple of value.

Note: note multiple_of ルールを使用するには、bcmath PHP 拡張機能が必要です。{note} The bcmath PHP extension[https://www.php.net/manual/en/book.bc.php] is required in order to use the multiple_of rule.

not_in:foo,bar,...not_in:foo,bar,...

フィールドが指定された値のリスト中に含まれていないことをバリデートします。Rule::notInメソッドのほうが、ルールの構成が読み書きしやすいでしょう。The field under validation must not be included in the given list of values. The Rule::notIn method may be used to fluently construct the rule:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['sprinkles', 'cherries']),
    ],
]);

not_regex:正規表現not_regex:pattern

フィールドが指定した正規表現と一致しないことをバリデートします。The field under validation must not match the given regular expression.

このルールは内部でPHPのpreg_match関数を使用しています。パターンは有効なデリミタを使用していることも含め、preg_matchが求めているフォーマットにしたがって指定する必要があります。たとえば:'email' => 'not_regex:/^. $/i'Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => 'not_regex:/^. $/i'.

Note: note regexnot_regexパターンを使用するとき、特に正規表現に|文字が含まれている場合は、|区切り文字を使用する代わりに配列を使用してバリデーションルールを指定する必要があります。{note} When using the regex / not_regex patterns, it may be necessary to specify your validation rules using an array instead of using | delimiters, especially if the regular expression contains a | character.

nullablenullable

フィールドはnullであることを許容します。The field under validation may be null.

numericnumeric

フィールドは数値であることをバリデートします。The field under validation must be numeric[https://www.php.net/manual/en/function.is-numeric.php].

passwordpassword

フィールドは、認証済みユーザーのパスワードと一致する必要があります。The field under validation must match the authenticated user's password.

Note: note このルールはLaravel9で削除するため、current_passwordへ名前を変更しました。代わりに現在のパスワードルールを使用してください。{note} This rule was renamed to current_password with the intention of removing it in Laravel 9. Please use the Current Password[#rule-current-password] rule instead.

presentpresent

フィールドが存在していることをバリデートしますが、存在していれば空を許します。The field under validation must be present in the input data but can be empty.

prohibitedprohibited

フィールドが空であるか、存在していないことをバリデートします。The field under validation must be empty or not present.

prohibited_if:anotherfield,value,...prohibited_if:anotherfield,value,...

anotherfieldフィールドが任意のvalueと等しい場合、対象のフィールドは空であるか、存在しないことをバリデートします。The field under validation must be empty or not present if the anotherfield field is equal to any value.

prohibited_unless:anotherfield,value,...prohibited_unless:anotherfield,value,...

anotherfielフィールドが任意のvalueと等しくない場合、対象のフィールドは空であるか、存在していないことをバリデートします。The field under validation must be empty or not present unless the anotherfield field is equal to any value.

prohibits:anotherfield,...prohibits:anotherfield,...

フィールドが存在する場合、anotherfieldで指定したフィールドが、たとえ空であっても1つも存在していないことをバリデートします。If the field under validation is present, no fields in anotherfield can be present, even if empty.

regex:正規表現regex:pattern

フィールドが指定された正規表現にマッチすることをバリデートします。The field under validation must match the given regular expression.

このルールは内部でPHPのpreg_match関数を使用しています。パターンは有効なデリミタを使用していることも含め、preg_matchが求めているフォーマットにしたがって指定する必要があります。たとえば:'email' => 'regex:/^. @. $/i'Internally, this rule uses the PHP preg_match function. The pattern specified should obey the same formatting required by preg_match and thus also include valid delimiters. For example: 'email' => 'regex:/^. @. $/i'.

Note: note regexnot_regexパターンを使用するとき、特に正規表現に|文字が含まれている場合は、|区切り文字を使用する代わりに、配列でルールを指定する必要があります。{note} When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using | delimiters, especially if the regular expression contains a | character.

requiredrequired

フィールドが入力データに存在しており、かつ空でないことをバリデートします。フィールドは以下の条件の場合、「空」であると判断されます。The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:

  • 値がnullである。The value is null.
  • 値が空文字列である。The value is an empty string.
  • 値が空の配列か、空のCountableオブジェクトである。The value is an empty array or empty Countable object.
  • 値がパスのないアップロード済みファイルである。The value is an uploaded file with no path.

required_if:他のフィールド,,...required_if:anotherfield,value,...

他のフィールドのどれかと一致している場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty if the anotherfield field is equal to any value.

required_ifルールのより複雑な条件を作成したい場合は、Rule::requiredIfメソッドを使用できます。このメソッドは、ブール値またはクロージャを受け入れます。クロージャが渡されると、クロージャは「true」または「false」を返し、バリデーション中のフィールドが必要かどうかを示します。If you would like to construct a more complex condition for the required_if rule, you may use the Rule::requiredIf method. This method accepts a boolean or a closure. When passed a closure, the closure should return true or false to indicate if the field under validation is required:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf($request->user()->is_admin),
]);

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf(function () use ($request) {
        return $request->user()->is_admin;
    }),
]);

required_unless:他のフィールド,,...required_unless:anotherfield,value,...

他のフィールドのどれとも一致していない場合、このフィールドが存在し、かつ空でないことをバリデートします。これはnullでない限り、他のフィールドはリクエストデータに存在しなければならないという意味でもあります。もしnullrequired_unless:name,null)の場合は、比較フィールドがnullであるか、リクエストデータに比較フィールドが存在しない限り、バリデーション対象下のフィールドは必須です。The field under validation must be present and not empty unless the anotherfield field is equal to any value. This also means anotherfield must be present in the request data unless value is null. If value is null (required_unless:name,null), the field under validation will be required unless the comparison field is null or the comparison field is missing from the request data.

required_with:foo,bar,...required_with:foo,bar,...

指定した他のフィールドが一つでも存在している場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty only if any of the other specified fields are present and not empty.

required_with_all:foo,bar,...required_with_all:foo,bar,...

指定した他のフィールドがすべて存在している場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty only if all of the other specified fields are present and not empty.

required_without:foo,bar,...required_without:foo,bar,...

指定した他のフィールドのどれか一つでも存在していない場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty only when any of the other specified fields are empty or not present.

required_without_all:foo,bar,...required_without_all:foo,bar,...

指定した他のフィールドがすべて存在していない場合、このフィールドが存在し、かつ空でないことをバリデートします。The field under validation must be present and not empty only when all of the other specified fields are empty or not present.

same:フィールドsame:field

フィールドが、指定されたフィールドと同じ値であることをバリデートします。The given field must match the field under validation.

size:size:value

フィールドは指定されたと同じサイズであることをバリデートします。文字列の場合、は文字長です。数値項目の場合、は整数値(属性にnumericintegerルールを持っている必要があります)です。配列の場合、は配列の個数(count)です。ファイルの場合、はキロバイトのサイズです。The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value (the attribute must also have the numeric or integer rule). For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes. Let's look at some examples:

// 文字列長が12文字ちょうどであることをバリデートする
'title' => 'size:12';

// 指定された整数が10であることをバリデートする
'seats' => 'integer|size:10';

// 配列にちょうど5要素あることをバリデートする
'tags' => 'array|size:5';

// アップロードしたファイルが512キロバイトぴったりであることをバリデートする
'image' => 'file|size:512';

starts_with:foo,bar,...starts_with:foo,bar,...

フィールドが、指定した値のどれかで始まることをバリデートします。The field under validation must start with one of the given values.

stringstring

フィルードは文字列タイプであることをバリデートします。フィールドがnullであることも許す場合は、そのフィールドにnullableルールも指定してください。The field under validation must be a string. If you would like to allow the field to also be null, you should assign the nullable rule to the field.

timezonetimezone

timezone_identifiers_list PHP関数の値に基づき、フィールドがタイムゾーンとして識別されることをバリデートします。The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:テーブル,カラムunique:table,column

フィールドが、指定されたデータベーステーブルに存在しないことをバリデートします。The field under validation must not exist within the given database table.

カスタムテーブル/カラム名の指定Specifying A Custom Table / Column Name:

テーブル名を直接指定する代わりに、Eloquentモデルを指定することもできます。Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:

'email' => 'unique:App\Models\User,email_address'

columnオプションは、フィールドの対応するデータベースカラムを指定するために使用します。columnオプションが指定されていない場合、バリデーション中のフィールドの名前が使用されます。The column option may be used to specify the field's corresponding database column. If the column option is not specified, the name of the field under validation will be used.

'email' => 'unique:users,email_address'

カスタムデータベース接続の指定Specifying A Custom Database Connection

場合により、バリデータが行うデータベースクエリのカスタム接続を指定する必要があります。これには、接続名をテーブル名の前に追加します。Occasionally, you may need to set a custom connection for database queries made by the Validator. To accomplish this, you may prepend the connection name to the table name:

'email' => 'unique:connection.users,email_address'

指定されたIDのuniqueルールを無視するForcing A Unique Rule To Ignore A Given ID:

場合により、uniqueのバリデーション中に特定のIDを無視したいことがあります。たとえば、ユーザーの名前、メールアドレス、および場所を含む「プロファイルの更新」画面について考えてみます。メールアドレスが一意であることを確認したいでしょう。しかし、ユーザーが名前フィールドのみを変更し、メールフィールドは変更しない場合、ユーザーは当該電子メールアドレスの所有者であるため、バリデーションエラーが投げられるのは望ましくありません。Sometimes, you may wish to ignore a given ID during unique validation. For example, consider an "update profile" screen that includes the user's name, email address, and location. You will probably want to verify that the email address is unique. However, if the user only changes the name field and not the email field, you do not want a validation error to be thrown because the user is already the owner of the email address in question.

バリデータにユーザーIDを無視するように指示するには、ルールをスラスラと定義できるRuleクラスを使います。以下の例の場合、さらにルールを|文字を区切りとして使用する代わりに、バリデーションルールを配列として指定しています。To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

Note: note ユーザーがコントロールするリクエストの入力をignoreメソッドへ、決して渡してはいけません。代わりに、Eloquentモデルインスタンスの自動増分IDやUUIDのような、生成されたユニークなIDだけを渡してください。そうしなければ、アプリケーションがSQLインジェクション攻撃に対し、脆弱になります。{note} You should never pass any user controlled request input into the ignore method. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack.

モデルキーの値をignoreメソッドに渡す代わりに、モデルインスタンス全体を渡すこともできます。Laravelはモデルからキーを自動的に抽出します:Instead of passing the model key's value to the ignore method, you may also pass the entire model instance. Laravel will automatically extract the key from the model:

Rule::unique('users')->ignore($user)

もし、テーブルの主キーとしてid以外のカラム名を使用している場合は、ignoreメソッドを呼び出す時に、カラムの名前を指定してください。If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:

Rule::unique('users')->ignore($user->id, 'user_id')

uniqueルールはデフォルトで、バリデートしようとしている属性名と一致するカラムの同一性をチェックします。しかしながら、uniqueメソッドの第2引数として、異なったカラム名を渡すことも可能です。By default, the unique rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique method:

Rule::unique('users', 'email_address')->ignore($user->id),

追加のWHERE節を付け加えるAdding Additional Where Clauses:

whereメソッドを使用してクエリをカスタマイズすることにより、追加のクエリ条件を指定できます。たとえば、account_id列の値が1の検索レコードのみ検索するクエリ条件で絞り込むクエリを追加してみます。You may specify additional query conditions by customizing the query using the where method. For example, let's add a query condition that scopes the query to only search records that have an account_id column value of 1:

'email' => Rule::unique('users')->where(function ($query) {
    return $query->where('account_id', 1);
})

urlurl

フィールドが有効なURLであることをバリデートします。The field under validation must be a valid URL.

uuiduuid

フィールドが有効な、RFC 4122(バージョン1、3、4、5)universally unique identifier (UUID)であることをバリデートします。The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID).

条件付きでルールを追加するConditionally Adding Rules

フィールドが特定値を持つ場合にバリデーションを飛ばすSkipping Validation When Fields Have Certain Values

他のフィールドに指定値が入力されている場合は、バリデーションを飛ばしたい状況がときどき起きるでしょう。exclude_ifバリデーションルールを使ってください。appointment_datedoctor_nameフィールドは、has_appointmentフィールドがfalse値の場合バリデートされません。You may occasionally wish to not validate a given field if another field has a given value. You may accomplish this using the exclude_if validation rule. In this example, the appointment_date and doctor_name fields will not be validated if the has_appointment field has a value of false:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($data, [
    'has_appointment' => 'required|boolean',
    'appointment_date' => 'exclude_if:has_appointment,false|required|date',
    'doctor_name' => 'exclude_if:has_appointment,false|required|string',
]);

もしくは逆にexclude_unlessルールを使い、他のフィールドに指定値が入力されていない場合は、バリデーションを行わないことも可能です。Alternatively, you may use the exclude_unless rule to not validate a given field unless another field has a given value:

$validator = Validator::make($data, [
    'has_appointment' => 'required|boolean',
    'appointment_date' => 'exclude_unless:has_appointment,true|required|date',
    'doctor_name' => 'exclude_unless:has_appointment,true|required|string',
]);

項目存在時のバリデーションValidating When Present

状況によっては、フィールドがバリデーション対象のデータに存在する場合にのみ、フィールドに対してバリデーションチェックを実行したい場合があります。これをすばやく実行するには、sometimesルールをルールリストに追加します。In some situations, you may wish to run validation checks against a field only if that field is present in the data being validated. To quickly accomplish this, add the sometimes rule to your rule list:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

上の例ではemailフィールドが、$data配列の中に存在している場合のみバリデーションが実行されます。In the example above, the email field will only be validated if it is present in the $data array.

lightbulb">Tip!! フィールドが常に存在しているが、空であることをバリデートする場合は、この追加フィールドに対する注意事項を確認してください。{tip} If you are attempting to validate a field that should always be present but may be empty, check out this note on optional fields[#a-note-on-optional-fields].

複雑な条件のバリデーションComplex Conditional Validation

ときどきもっと複雑な条件のロジックによりバリデーションルールを追加したい場合もあります。たとえば他のフィールドが100より大きい場合のみ、指定したフィールドが入力されているかをバリデートしたいときなどです。もしくは2つのフィールドのどちらか一方が存在する場合は、両方共に値を指定する必要がある場合です。こうしたルールを付け加えるのも面倒ではありません。最初にValidatorインスタンスを生成するのは、固定ルールの場合と同じです。Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may wish to require a given field only if another field has a greater value than 100. Or, you may need two fields to have a given value only when another field is present. Adding these validation rules doesn't have to be a pain. First, create a Validator instance with your static rules that never change:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'email' => 'required|email',
    'games' => 'required|numeric',
]);

私たちのWebアプリケーションがゲームコレクター向けであると仮定しましょう。ゲームコレクターがアプリケーションに登録し、100を超えるゲームを所有している場合は、なぜこれほど多くのゲームを所有しているのかを説明してもらいます。たとえば、ゲームの再販店を経営している場合や、ゲームの収集を楽しんでいる場合などです。この要件を条件付きで追加するには、Validatorインスタンスでsometimesメソッドを使用できます。Let's assume our web application is for game collectors. If a game collector registers with our application and they own more than 100 games, we want them to explain why they own so many games. For example, perhaps they run a game resale shop, or maybe they just enjoy collecting games. To conditionally add this requirement, we can use the sometimes method on the Validator instance.

$validator->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});

sometimesメソッドに渡される最初の引数は、条件付きでバリデーションするフィールドの名前です。2番目の引数は、追加するルールのリストです。3番目の引数として渡すクロージャがtrueを返す場合、ルールが追加されます。この方法で、複雑な条件付きバリデーションを簡単に作成できます。複数のフィールドに条件付きバリデーションを一度に追加することもできます。The first argument passed to the sometimes method is the name of the field we are conditionally validating. The second argument is a list of the rules we want to add. If the closure passed as the third argument returns true, the rules will be added. This method makes it a breeze to build complex conditional validations. You may even add conditional validations for several fields at once:

$validator->sometimes(['reason', 'cost'], 'required', function ($input) {
    return $input->games >= 100;
});

lightbulb">Tip!! クロージャに渡される$inputパラメーターは、Illuminate\Support\Fluentのインスタンスであり、バリデーション中の入力とファイルへアクセスするために使用できます。{tip} The $input parameter passed to your closure will be an instance of Illuminate\Support\Fluent and may be used to access your input and files under validation.

複雑な条件の配列バリデーションComplex Conditional Array Validation

インデックスがわからない、入れ子になった同じ配列の中にある別のフィールドに基づいて、あるフィールドを検証したいことがあります。このような場合には、クロージャへ第2引数を渡してください。第2引数には、配列中のバリデーション対象の現アイテムが渡されます。Sometimes you may want to validate a field based on another field in the same nested array whose index you do not know. In these situations, you may allow your closure to receive a second argument which will be the current individual item in the array being validated:

$input = [
    'channels' => [
        [
            'type' => 'email',
            'address' => 'abigail@example.com',
        ],
        [
            'type' => 'url',
            'address' => 'https://example.com',
        ],
    ],
];

$validator->sometimes('channels.*.address', 'email', function ($input, $item) {
    return $item->type === 'email';
});

$validator->sometimes('channels.*.address', 'url', function ($input, $item) {
    return $item->type !== 'email';
});

クロージャに渡される$inputパラメータと同様に、$itemパラメータは属性データが配列の場合はIlluminate\Support\Fluentのインスタンス、そうでない場合は文字列になります。Like the $input parameter passed to the closure, the $item parameter is an instance of Illuminate\Support\Fluent when the attribute data is an array; otherwise, it is a string.

配列のバリデーションValidating Arrays

arrayバリデーションルールのドキュメントで説明したように、arrayルールは、許可する配列キーのリストを受け入れます。配列内にその他のキーが存在する場合、バリデーションは失敗します。As discussed in the array validation rule documentation[#rule-array], the array rule accepts a list of allowed array keys. If any additional keys are present within the array, validation will fail:

use Illuminate\Support\Facades\Validator;

$input = [
    'user' => [
        'name' => 'Taylor Otwell',
        'username' => 'taylorotwell',
        'admin' => true,
    ],
];

Validator::make($input, [
    'user' => 'array:username,locale',
]);

一般的には、配列内に存在を許す配列キーを常に指定する必要があります。そうしないと、バリデータのvalidatevalidatedメソッドは、配列とそのすべてのキーを含むバリデート済みデータをすべて返してしまいます。In general, you should always specify the array keys that are allowed to be present within your array. Otherwise, the validator's validate and validated methods will return all of the validated data, including the array and all of its keys, even if those keys were not validated by other nested array validation rules.

バリデートできなかった配列キーの除外Excluding Unvalidated Array Keys

必要に応じ、許可するキーのリストを指定せずにarrayルールを使用した場合でも、Laravelのバリデータが返す「検証済み」データに未検証の配列キーを含めないように指示できます。そうするには、アプリケーションのAppServiceProviderbootメソッドでバリデータのexcludeUnvalidatedArrayKeysメソッドを呼び出してください。それによりバリデータは、ネストする配列ルールにより検証された場合にのみ返される「検証済み」データへ配列キーを含めます。If you would like, you may instruct Laravel's validator to never include unvalidated array keys in the "validated" data it returns, even if you use the array rule without specifying a list of allowed keys. To accomplish this, you may call the validator's excludeUnvalidatedArrayKeys method in the boot method of your application's AppServiceProvider. After doing so, the validator will include array keys in the "validated" data it returns only when those keys were specifically validated by nested array rules[#validating-arrays]:

use Illuminate\Support\Facades\Validator;

/**
 * 全アプリケーションサービスの登録
 *
 * @return void
 */
public function boot()
{
    Validator::excludeUnvalidatedArrayKeys();
}

ネストした配列入力のバリデーションValidating Nested Array Input

ネストした配列ベースフォームの入力フィールドをバリデーションするのが、面倒である必要はありません。配列内の属性をバリデーションするには、「ドット記法」が使えます。たとえば、HTTPリクエストにphotos[profile]フィールドが含まれている場合、次のように検証します。Validating nested array based form input fields doesn't have to be a pain. You may use "dot notation" to validate attributes within an array. For example, if the incoming HTTP request contains a photos[profile] field, you may validate it like so:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'photos.profile' => 'required|image',
]);

配列の各要素をバリデーションすることもできます。たとえば、特定の配列入力フィールドの各メールが一意であることをバリデーションするには、次のようにします。You may also validate each element of an array. For example, to validate that each email in a given array input field is unique, you may do the following:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

同様に、言語ファイルのカスタムバリデーションメッセージを指定するときに*文字を使用すると、配列ベースのフィールドに単一のバリデーションメッセージを簡単に使用できます。Likewise, you may use the * character when specifying custom validation messages in your language files[#custom-messages-for-specific-attributes], making it a breeze to use a single validation message for array based fields:

'custom' => [
    'person.*.email' => [
        'unique' => 'Each person must have a unique email address',
    ]
],

パスワードのバリデーションValidating Passwords

パスワードが十分なレベルの複雑さがあることを確認するために、LaravelのPasswordルールオブジェクトを使用できます。To ensure that passwords have an adequate level of complexity, you may use Laravel's Password rule object:

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;

$validator = Validator::make($request->all(), [
    'password' => ['required', 'confirmed', Password::min(8)],
]);

Passwordルールオブジェクトを使用すると、文字・数字・記号を最低1文字必要にしたり、文字種を組み合わせたりのように、パスワードの指定をアプリケーションで使用する複雑さの要件に合うよう簡単にカスタマイズできます。The Password rule object allows you to easily customize the password complexity requirements for your application, such as specifying that passwords require at least one letter, number, symbol, or characters with mixed casing:

// 最低8文字必要
Password::min(8)

// 最低1文字の文字が必要
Password::min(8)->letters()

// 最低大文字小文字が1文字ずつ必要
Password::min(8)->mixedCase()

// 最低一文字の数字が必要
Password::min(8)->numbers()

// 最低一文字の記号が必要
Password::min(8)->symbols()

さらに、uncompromisedメソッドを使って、公開されているパスワードのデータ漏洩によるパスワード漏洩がないことを確認することもできます。In addition, you may ensure that a password has not been compromised in a public password data breach leak using the uncompromised method:

Password::min(8)->uncompromised()

内部的には、Passwordルールオブジェクトは、k-Anonymityモデルを使用して、ユーザーのプライバシーやセキュリティを犠牲にすることなく、パスワードがhaveibeenpwned.comサービスを介してリークされているかを判断します。Internally, the Password rule object uses the k-Anonymity[https://en.wikipedia.org/wiki/K-anonymity] model to determine if a password has been leaked via the haveibeenpwned.com[https://haveibeenpwned.com] service without sacrificing the user's privacy or security.

デフォルトでは、データリークに少なくとも1回パスワードが表示されている場合は、侵害されたと見なします。uncompromisedメソッドの最初の引数を使用してこのしきい値をカスタマイズできます。By default, if a password appears at least once in a data leak, it will be considered compromised. You can customize this threshold using the first argument of the uncompromised method:

// 同一のデータリークにおいて、パスワードの出現回数が3回以下であることを確認
Password::min(8)->uncompromised(3);

もちろん、上記の例ですべてのメソッドをチェーン化することができます。Of course, you may chain all the methods in the examples above:

Password::min(8)
    ->letters()
    ->mixedCase()
    ->numbers()
    ->symbols()
    ->uncompromised()

デフォルトパスワードルールの定義Defining Default Password Rules

パスワードのデフォルトバリデーションルールをアプリケーションの一箇所で指定できると便利でしょう。クロージャを引数に取るPassword::defaultsメソッドを使用すると、これを簡単に実現できます。defaultsメソッドへ渡すクロージャは、パスワードルールのデフォルト設定を返す必要があります。通常、defaultsルールはアプリケーションのサービスプロバイダの1つのbootメソッド内で呼び出すべきです。You may find it convenient to specify the default validation rules for passwords in a single location of your application. You can easily accomplish this using the Password::defaults method, which accepts a closure. The closure given to the defaults method should return the default configuration of the Password rule. Typically, the defaults rule should be called within the boot method of one of your application's service providers:

use Illuminate\Validation\Rules\Password;

/**
 * アプリケーションの全サービスの初期処理
 *
 * @return void
 */
public function boot()
{
    Password::defaults(function () {
        $rule = Password::min(8);

        return $this->app->isProduction()
                    ? $rule->mixedCase()->uncompromised()
                    : $rule;
    });
}

そして、バリデーションで特定のパスワードへデフォルトルールを適用したい場合に、引数なしでdefaultsメソッドを呼び出します。Then, when you would like to apply the default rules to a particular password undergoing validation, you may invoke the defaults method with no arguments:

'password' => ['required', Password::defaults()],

時には、デフォルトのパスワードバリデーションルールへ追加ルールを加えたい場合があります。このような場合には、rulesメソッドを使用します。Occasionally, you may want to attach additional validation rules to your default password validation rules. You may use the rules method to accomplish this:

use App\Rules\ZxcvbnRule;

Password::defaults(function () {
    $rule = Password::min(8)->rules([new ZxcvbnRule]);

    // ...
});

カスタムバリデーションルールCustom Validation Rules

ルールオブジェクトの使用Using Rule Objects

Laravelは有用な数多くのバリデーションルールを提供しています。ただし、独自のものを指定することもできます。カスタムバリデーションルールを登録する1つの方法は、ルールオブジェクトを使用することです。新しいルールオブジェクトを生成するには、make:ruleArtisanコマンドを使用できます。このコマンドを使用して、文字列が大文字であることを確認するルールを生成してみましょう。Laravelは新しいルールをapp/Rulesディレクトリに配置します。このディレクトリが存在しない場合、Artisanコマンドを実行してルールを作成すると、Laravelがそのディレクトリを作成します。Laravel provides a variety of helpful validation rules; however, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. To generate a new rule object, you may use the make:rule Artisan command. Let's use this command to generate a rule that verifies a string is uppercase. Laravel will place the new rule in the app/Rules directory. If this directory does not exist, Laravel will create it when you execute the Artisan command to create your rule:

php artisan make:rule Uppercase

ルールを生成したら、動作を定義する準備ができました。ルールオブジェクトは2つのメソッドを含みます。passesmessageです。passesメソッドは属性の値と名前を受け取り、その属性値が有効であればtrue、無効であればfalseを返します。messageメソッドは、バリデーション失敗時に使用する、バリデーションエラーメッセージを返します。Once the rule has been created, we are ready to define its behavior. A rule object contains two methods: passes and message. The passes method receives the attribute value and name, and should return true or false depending on whether the attribute value is valid or not. The message method should return the validation error message that should be used when validation fails:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    /**
     * バリデーションの成功を判定
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return strtoupper($value) === $value;
    }

    /**
     * バリデーションエラーメッセージの取得
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

もちろん、翻訳ファイルのエラーメッセージを返したい場合は、messageメソッドからtransヘルパを呼び出せます。You may call the trans helper from your message method if you would like to return an error message from your translation files:

/**
 * バリデーションエラーメッセージの取得
 *
 * @return string
 */
public function message()
{
    return trans('validation.uppercase');
}

ルールが定義できたら、他のバリデーションルールと一緒に、ルールオブジェクトのインスタンスをバリデータへ渡し、指定します。Once the rule has been defined, you may attach it to a validator by passing an instance of the rule object with your other validation rules:

use App\Rules\Uppercase;

$request->validate([
    'name' => ['required', 'string', new Uppercase],
]);

追加データへのアクセスAccessing Additional Data

カスタムバリデーションルールクラスがバリデーション下の他のすべてのデータへアクセスする必要がある場合、そのルールクラスにIlluminate\Contracts\Validation\DataAwareRuleインターフェイスを実装してください。このインターフェイスは、クラスへsetData メソッドの定義を要求します。このメソッドはLaravelにより自動的に(バリデーション処理前に)、バリデーション対象の全データで呼び出されます。If your custom validation rule class needs to access all of the other data undergoing validation, your rule class may implement the Illuminate\Contracts\Validation\DataAwareRule interface. This interface requires your class to define a setData method. This method will automatically be invoked by Laravel (before validation proceeds) with all of the data under validation:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\DataAwareRule;

class Uppercase implements Rule, DataAwareRule
{
    /**
     * バリデーション下の全データ
     *
     * @var array
     */
    protected $data = [];

    // ...

    /**
     * バリデーション下のデータをセット
     *
     * @param  array  $data
     * @return $this
     */
    public function setData($data)
    {
        $this->data = $data;

        return $this;
    }
}

または、バリデーションルールが、バリデーションを行うバリデータインスタンスへのアクセスを必要とする場合は、ValidatorAwareRuleインターフェイスを実装してください。Or, if your validation rule requires access to the validator instance performing the validation, you may implement the ValidatorAwareRule interface:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;

class Uppercase implements Rule, ValidatorAwareRule
{
    /**
     * バリデータインスタンス
     *
     * @var \Illuminate\Validation\Validator
     */
    protected $validator;

    // ...

    /**
     * 現用バリデータのセット
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return $this
     */
    public function setValidator($validator)
    {
        $this->validator = $validator;

        return $this;
    }
}

クロージャの使用Using Closures

アプリケーション全体でカスタムルールの機能が1回だけ必要な場合は、ルールオブジェクトの代わりにクロージャを使用できます。クロージャは、属性の名前、属性の値、およびバリデーションが失敗した場合に呼び出す必要がある$failコールバックを受け取ります。If you only need the functionality of a custom rule once throughout your application, you may use a closure instead of a rule object. The closure receives the attribute's name, the attribute's value, and a $fail callback that should be called if validation fails:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'title' => [
        'required',
        'max:255',
        function ($attribute, $value, $fail) {
            if ($value === 'foo') {
                $fail('The '.$attribute.' is invalid.');
            }
        },
    ],
]);

暗黙のルールImplicit Rules

デフォルトでは、バリデーションされる属性が存在しないか、空の文字列が含まれている場合、カスタムルールを含む通常のバリデーションルールは実行されません。たとえば、uniqueルールは空の文字列に対して実行されません。By default, when an attribute being validated is not present or contains an empty string, normal validation rules, including custom rules, are not run. For example, the unique[#rule-unique] rule will not be run against an empty string:

use Illuminate\Support\Facades\Validator;

$rules = ['name' => 'unique:users,name'];

$input = ['name' => ''];

Validator::make($input, $rules)->passes(); // true

属性が空の場合でもカスタムルールを実行するには、ルールは属性が必須であることを意味する必要があります。「暗黙の」ルールを作成するには、Illuminate\Contracts\Validation\ImplicitRuleインターフェイスを実装します。このインターフェイスは、バリデータの「マーカーインターフェイス」として機能します。したがって、通常のRuleインターフェイスで必要なメソッド以外に実装する必要のある追加のメソッドは含まれていません。For a custom rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create an "implicit" rule, implement the Illuminate\Contracts\Validation\ImplicitRule interface. This interface serves as a "marker interface" for the validator; therefore, it does not contain any additional methods you need to implement beyond the methods required by the typical Rule interface.

新しい暗黙のルールオブジェクトを生成するには、make:rule Artisanコマンドに--implicitオプションを付けて使用してください。To generate a new implicit rule object, you may use the make:rule Artisan command with the --implicit option :

 php artisan make:rule Uppercase --implicit

Note: note 「暗黙の」ルールは、属性が必要であることを暗黙的にします。欠落している属性または空の属性を実際に無効にするかどうかは、あなた次第です。{note} An "implicit" rule only implies that the attribute is required. Whether it actually invalidates a missing or empty attribute is up to you.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作