Readouble

Laravel 5.dev バリデーション

基本の使用法Basic Usage

Laravelにはシンプルで便利なValidationクラスが用意されており、データーの正当性確認やエラーメッセージの取得ができます。Laravel ships with a simple, convenient facility for validating data and retrieving validation error messages via the Validation class.

基本的なバリデーション例Basic Validation Example

$validator = Validator::make(
	array('name' => 'Dayle'),
	array('name' => 'required|min:5')
);

makeメソッドに渡す最初の引数はバリデーションを行うデーターです。2つ目の引数はデーターに適用するバリデーションルールです。The first argument passed to the make method is the data under validation. The second argument is the validation rules that should be applied to the data.

ルールの指定に配列を使用するUsing Arrays To Specify Rules

複数のルール指定はパイプ(縦線)で区切るか、配列で分割し指定します。Multiple rules may be delimited using either a "pipe" character, or as separate elements of an array.

$validator = Validator::make(
	array('name' => 'Dayle'),
	array('name' => array('required', 'min:5'))
);

複数のフィールドをバリデーションするValidating Multiple Fields

$validator = Validator::make(
    array(
        'name' => 'Dayle',
        'password' => 'lamepassword',
        'email' => 'email@example.com'
    ),
    array(
        'name' => 'required',
        'password' => 'required|min:8',
        'email' => 'required|email|unique:users'
    )
);

Validatorインスタンスが生成されたら、fails(もしくはpasses)メソッドを使用し、バリデーションを実行します。Once a Validator instance has been created, the fails (or passes) method may be used to perform the validation.

if ($validator->fails())
{
	// 与えられたデーターはバリデーションをパスしなかった
}

バリデーションが失敗すると、バリデーターよりエラーメッセージが取得できます。If validation has failed, you may retrieve the error messages from the validator.

$messages = $validator->messages();

メッセージではなく、バリデーションで失敗したことを示す配列へアクセスすることも可能です。使用するにはfailedメソッドを使ってくだい。You may also access an array of the failed validation rules, without messages. To do so, use the failed method:

$failed = $validator->failed();

ファイルのバリデーションValidating Files

Validatorクラスはファイルに対し、sizemimesなどのようないくつかのバリデーションルールを提供しています。ファイルをバリデーションする場合は、他のデータと一緒にバリデーターへ渡してください。The Validator class provides several rules for validating files, such as size, mimes, and others. When validating files, you may simply pass them into the validator with your other data.

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

バリデーションには、完了した後に実行するコールバックを追加することもできます。これにより、簡単に追加の確認をしたり、メッセージコレクションへエラーメッセージを追加したりさえできます。これを行うには、バリデーションインスタンスに対し、afterメソッドを使用してください。The validator also allows you to 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, use 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())
{
	//
}

必要に応じて、多くのafterコールバックを追加することもできます。You may add as many after callbacks to a validator as needed.

コントローラーバリデーションController Validation

もちろん、バリデーションを行うために、毎回手動でValidatorインスタンスを生成し、確認するのは面倒ですよね。心配ご無用、別の方法もあります!ベースのApp\Http\Controllers\Controllerクラスは、LaravelのValidatesRequestsトレイトを使っています。このトレイトは、送られてくるHTTPリクエストをバリデーションするための便利なメソッドを一つ提供しています。ご覧ください。Of course, manually creating and checking a Validator instance each time you do validation is a headache. Don't worry, you have other options! The base App\Http\Controllers\Controller class included with Laravel uses a ValidatesRequests trait. This trait provides a single, convenient method for validating incoming HTTP requests. Here's what it looks like:

/**
 * 投稿されたブログ投稿を保存する
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
	$this->validate($request, [
		'title' => 'required|unique|max:255',
		'body' => 'required',
	]);

	//
}

バリデーションが通れば、コードは通常通り実行されます。しかし、バリデーションに失敗すると、Illuminate\Contracts\Validation\ValidationExceptionが投げられます。この例外は自動的に補足され、ユーザーが前にアクセスしたURLへのリダイレクトを生成します。バリデーションエラーも自動的に、セッションへフラッシュデータとして保存されます!If validation passes, your code will keep executing normally. However, if validation fails, an Illuminate\Contracts\Validation\ValidationException will be thrown. This exception is automatically caught and a redirect is generated to the user's previous location. The validation errors are even automatically flashed to the session!

もし、やって来たリクエストがAJAXリクエストであれば、リダイレクトは生成されません。代わりに、バリデーションエラーを表すJSONを含んだ、422ステータスコードのHTTPレスポンスがブラウザへ返されます。If the incoming request was an AJAX request, no redirect will be generated. Instead, an HTTP response with a 422 status code will be returned to the browser containing a JSON representation of the validation errors.

つまり、通常の書き方をした同等のコードはこのようになります。For example, here is the equivalent code written manually:

/**
 * 投稿されたブログ投稿を保存する
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
	$v = Validator::make($request->all(), [
		'title' => 'required|unique|max:255',
		'body' => 'required',
	]);

	if ($v->fails())
	{
		return redirect()->back()->withErrors($v->errors());
	}

	//
}

フラッシュデータとして保存されるエラー形式のカスタマイズCustomizing The Flashed Error Format

バリデーションが失敗した時に、フラッシュデーターとして保存されるバリデーションエラーの形式をカスタマイズしたければ、ベースコントローラーのformatValidationErrorsをオーバーライドしてください。Illuminate\Validation\Validatorクラスをファイルの先頭でインポートするのを忘れないでください。If you wish to customize the format of the validation errors that are flashed to the session when validation fails, override the formatValidationErrors on your base controller. Don't forget to import the Illuminate\Validation\Validator class at the top of the file:

/**
 * {@inheritdoc}
 */
protected function formatValidationErrors(Validator $validator)
{
	return $validator->errors()->all();
}

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

より複雑なバリデーションのシナリオでは、「フォームリクエスト」を生成したほうが良いでしょう。フォームリクエストは、バリデーションロジックを含んだカスタムリクエストクラスです。フォームリクエストクラスを作成するには、make:request Artisan CLIコマンドを使用します。For more complex validation scenarios, you may wish to create a "form request". Form requests are custom request classes that contain validation logic. To create a form request class, use the make:request Artisan CLI command:

php artisan make:request StoreBlogPostRequest

生成されたクラスは、app/Http/Requestディレクトリーへ設置されます。では、バリデーションルールを少しrulesメソッドへ追加してみましょう。The generated class will be placed in the app/Http/Requests directory. Let's add a few validation rules to the rules method:

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

では、どのようにバリデーションルールを実行するのでしょうか?必要なのは、コントローラーのメソッドで、このリクエストをタイプヒントで指定することです。So, how are the validation rules executed? All you need to do is type-hint the request on your controller method:

/**
 * やってきたブログ投稿を保存する。
 *
 * @param  StoreBlogPostRequest  $request
 * @return Response
 */
public function store(StoreBlogPostRequest $request)
{
	// やってきたリクエストは有効だった…
}

やってきたフォームリクエストは、コントローラーメソッドが呼び出される前に確認されます。既に、バリデーション済みです!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. It has already been validated!

バリデーションに失敗すると、前のアドレスにユーザーを戻すために、リダイレクトレスポンスが生成されます。エラーも表示できるように、フラッシュデーターとしてセッションに保存されます。もし、リクエストがAJAXリクエストであれば、バリデーションエラーを表現する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 AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.

フォームリクエスト権限Authorizing Form Requests

フォームリクエストクラスは、authorizeメソッドも用意しています。このメソッドでは、認証されているユーザーが、指定されたリソースを更新する権限を実際に持っているのかを確認します。例えば、ユーザーがブログポストのコメントを更新しようとしているなら、本人のコメントなのでしょうか?調べてみましょう。The form request class also contains an authorize method. Within this method, you may check if the authenticated user actually has the authority to update a given resource. For example, if a user is attempting to update a blog post comment, do they actually own that comment? For example:

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

	return Comment::where('id', $commentId)
                  ->where('user_id', Auth::id())->exists();
}

上の例の中の、routeメソッド呼び出しに注目してください。このメソッドで、例えば{comment}パラメーターのような、呼びだされているルートのURIパラメーター定義にアクセスさせてくれます。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}');

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

アプリケーションの他の場所で、認証のロジックを行おうと設計しているのでしたら、シンプルにauthorizeメソッドから、trueを返してください。If you plan to have authorization logic in another part of your application, simply return true from the authorize method:

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

フラッシュデータとして保存されるエラー形式のカスタマイズCustomizing The Flashed Error Format

バリデーションが失敗した時に、フラッシュデーターとして保存されるバリデーションエラーの形式をカスタマイズしたければ、ベースリクエスト(App\Http\Requests\Request)のformatValidationErrorsをオーバーライドしてください。Illuminate\Validation\Validatorクラスをファイルの先頭でインポートするのを忘れないでください。If you wish to customize the format of the validation errors that are flashed to the session when validation fails, override the formatValidationErrors on your base request (App\Http\Requests\Request). Don't forget to import the Illuminate\Validation\Validator class at the top of the file:

/**
 * {@inheritdoc}
 */
protected function formatErrors(Validator $validator)
{
	return $validator->errors()->all();
}

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

Validatorのインスタンスに対し、messagesメソッドを呼びだせば、エラーメッセージを操作するのに便利な様々なメソッドを持つMessageBagインスタンスが取得できます。After calling the messages method on a Validator instance, you will receive a MessageBag instance, which has a variety of convenient methods for working with error messages.

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

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

あるフィールドの全エラーメッセージを取得するRetrieving All Error Messages For A Field

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

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

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

あるフィールドにメッセージが存在するか調べるDetermining If Messages Exist For A Field

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

エラーメッセージをフォーマットを指定し取得するRetrieving An Error Message With A Format

echo $messages->first('email', '<p>:message</p>');

デフォルトでは、エラーメッセージはBootstrapコンパチブルな形式が使われます。Note: By default, messages are formatted using Bootstrap compatible syntax.

全エラーメッセージをフォーマット指定で取得するRetrieving All Error Messages With A Format

foreach ($messages->all('<li>:message</li>') as $message)
{
	//
}

エラーメッセージとビューError Messages & Views

一度バリデーションを実行したら、エラーメッセージをビューで簡単に表示する方法が欲しくなるでしょう。Laravelでは便利に行えます。以下のルートを参考にしてください。Once you have performed validation, you will need an easy way to get the error messages back to your views. This is conveniently handled by Laravel. Consider the following routes as an example:

Route::get('register', function()
{
	return View::make('user.register');
});

Route::post('register', function()
{
	$rules = array(...);

	$validator = Validator::make(Input::all(), $rules);

	if ($validator->fails())
	{
		return redirect('register')->withErrors($validator);
	}
});

バリデーションに失敗した場合、ValidatorインスタンスをリダイレクトのwithErrorsメソッドに渡していることに注目してください。このメソッドはセッションにエラーメッセージをフラッシュデーターとして保存し、次のリクエストで使用できるようにします。Note that when validation fails, we pass the Validator instance to the Redirect using the withErrors method. This method will flash the error messages to the session so that they are available on the next request.

しかし、GETルートの中で明示的にエラーメッセージをビューに結合していないことにも注目してください。これは常にLaravelがセッションにerrorsが存在しないかチェックしており、存在時は自動的にビューに結びつけてくれるからです。ですから、$errors変数はいつでも全リクエスト中の、全ビューで使用でき、あなたは$errorsはいつでも定義済みだと確信し、安心して使用できるのです。$errors変数はMessageBagインスタンスです。However, notice that we do not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will always check for errors in the session data, and automatically bind them to the view if they are available. So, it is important to note that an $errors variable will always be available in all of your views, on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used. The $errors variable will be an instance of MessageBag.

ですから、リダイレクトした後に、ビューと自動的に結び付けられた$errors変数を便利に利用してください。So, after redirection, you may utilize the automatically bound $errors variable in your view:

<?php echo $errors->first('email'); ?>

名前付きエラーBagNamed Error Bags

一つのページに複数のフォームがある場合、エラーのMessageBagに名前を付けたいこともあるでしょう。これにより、特定のフォームに対するエラーメッセージを取得できるようになります。withErrorsへの第2引数として、名前を渡すだけです。If you have multiple forms on a single page, you may wish to name the MessageBag of errors. This will allow you to retrieve the error messages for a specific form. Simply 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:

<?php echo $errors->login->first('email'); ?>

用意されているバリデーションルールAvailable Validation Rules

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

acceptedaccepted

そのフィールドがyeson、もしくは1であることをバリデートします。これは「サービス利用規約」同意のバリデーションに便利です。The field under validation must be yes, on, or 1. This is useful for validating "Terms of Service" acceptance.

active_urlactive_url

フィルドがPHPの機能であるcheckdnsrrを通して、有効なURLであるかをバリデートします。The field under validation must be a valid URL according to the checkdnsrr PHP function.

after:日付after:date

フィールドの値が与えられた日付以降であるかバリデーションします。日付はPHPのstrtotime関数で処理されます。The field under validation must be a value after a given date. The dates will be passed into the PHP strtotime function.

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

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

before:日付before:date

フィールドが与えられた日付より前であることをバリデートします。日付はPHPのstrtotime関数で処理されます。The field under validation must be a value preceding the given date. The dates will be passed into the PHP strtotime function.

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

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

フィールドがそのフィールド名+_confirmationフィールドと同じ値であることをバリデートします。例えば、バリデーションするフィールドがpasswordであれば、password_confirmationフィールドが入力に存在していなければなりません。The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

datedate

パリデーションされる値はPHP関数のstrtotimeを使用し確認されます。The field under validation must be a valid date according to the strtotime PHP function.

date_format:フォーマットdate_format:format

バリデーションされる値はフォーマット定義と一致するか、PHP関数のdate_parse_from_formatを使用し確認されます。The field under validation must match the format defined according to the date_parse_from_format PHP function.

different:フィールドdifferent:field

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

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 have a length between the given min and max.

emailemail

フィールドがメールアドレスとして正しいことをバリデートします。The field under validation must be formatted as an e-mail address.

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

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

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

'state' => 'exists:states'

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

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

さらにクエリーへWHERE節として追加される条件を追加することも可能です。You may also specify more conditions that will be added as "where" clauses to the query:

'email' => 'exists:staff,email,account_id,1'

NULLを"where"節の値として渡せば、データベースの値がNULLであることを追加でチェックできます。Passing NULL as a "where" clause value will add a check for a NULL database value:

'email' => 'exists:staff,email,deleted_at,NULL'

imageimage

フィールドで指定されたファイルが画像(jpg、png、bmp、gif、svg)であることをバリデートします。The file under validation must be an image (jpeg, png, bmp, gif, or svg)

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

フィールドが指定されたリストの中の値に含まれていることをバリデートします。The field under validation must be included in the given list of values.

integerinteger

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

ipip

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

max:max:value

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

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

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

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

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

min:min:value

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

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

フィールドが指定されたリストの中の値に含まれていないことをバリデートします。The field under validation must not be included in the given list of values.

numericnumeric

フィールドは数値であることをバリデートします。The field under validation must have a numeric value.

regex:正規表現regex:pattern

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

注目:regexパターンを使用する場合は、ルールをパイプ(縦棒)で区切るのではなく、配列で指定することが必要になります。特に正規表現に縦棒を含んでいる場合は該当します。Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

requiredrequired

フィールドに入力データーが存在することをバリデートします。The field under validation must be present in the input data.

required_with_all:foo,bar...required_if:field,value,...

引数で指定されたフィールドのうち、全てが存在している場合のみ、フィールドが入力されていることをバリデートします。The field under validation must be present if the field field is equal to any value.

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

引数で指定されたフィールドのうち、どれかが存在している場合のみ、フィールドが入力されていることをバリデートします。The field under validation must be present only if any of the other specified fields are present.

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

引数で指定されたフィールドのうち、全てが存在している場合のみ、フィールドが入力されていることをバリデートします。The field under validation must be present only if all of the other specified fields are present.

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

フィールドは、指定された他のフィールドのうちどれかが存在しない場合のみ、この項目が入力されていることをバリデートします。The field under validation must be present only when any of the other specified fields are not present.

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

フィールドは、指定された他のフィールド全部が存在しない場合のみ、この項目が入力されていることをバリデートします。The field under validation must be present only when all of the other specified fields are not present.

same:フィールドsame:field

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

size:size:value

フィールドは指定されたと同じサイズであることをバリデートします。文字列の場合、は文字長です。数値項目の場合、は整数値です。ファイルの場合、はキロバイトのサイズです。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. For files, size corresponds to the file size in kilobytes.

string:string:value

フィルードは文字列タイプであることをバリデートします。The field under validation must be a string type.

timezonetimezone

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

unique:テーブル,カラム,除外ID,IDカラムunique:table,column,except,idColumn

フィールドは指定されたデータベースで一意であることをバリデートします。columnオプションが指定されない場合、フィールド名が使用されます。The field under validation must be unique on a given database table. If the column option is not specified, the field name will be used.

uniqueルールの基本的な使用例Basic Usage Of Unique Rule

'email' => 'unique:users'

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

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

指定されたIDを無視するForcing A Unique Rule To Ignore A Given ID

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

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

さらにクエリーへWHERE節として追加される条件を追加することも可能です。You may also specify more conditions that will be added as "where" clauses to the query:

'email' => 'unique:users,email_address,NULL,id,account_id,1'

上記のルールでは、同一かチェックする対象は、account_id1の行のみになります。In the rule above, only rows with an account_id of 1 would be included in the unique check.

urlurl

フィールドがURLの形式であることをバリデートします。The field under validation must be formatted as an URL.

**注目:**この機能は、PHPのfilter_varメソッドを使用しています。Note: This function uses PHP's filter_var method.

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

ある状況では、そのフィールドが入力配列の中に存在する場合のみ、バリデーションを実行したいことがあると思います。これを簡単に行うには、sometimesルールを追加してください。In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

$v = Validator::make($data, array(
	'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.

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

時々(sometime)、他のフィールド値が100以上の場合のみ指定したフィールド入力を必須にしたい場合もあるでしょう。もしくは、あるフィールドを指定する場合だけ、2つのフィールドが必要な場合もあるでしょう。この様なバリデーションルールを追加する場合でも、手間はかかりません。最初に固定ルールによりValidatorインスタンスを作成するのは変わりません。Sometimes 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:

$v = Validator::make($data, array(
	'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 re-sell shop, or maybe they just enjoy collecting. To conditionally add this requirement, we can use the sometimes method on the Validator instance.

$v->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 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:

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

**注目:**クロージャーに渡される$inputパラメーターは、Illuminate\Support\Fluentのインスタンスで、フィールドと入力値にアクセスするためのオブジェクトです。Note: The $input parameter passed to your Closure will be an instance of Illuminate\Support\Fluent and may be used as an object to access your input and files.

カスタムエラーメッセージCustom Error Messages

必要であれば、デフォルトのエラーメッセージの代わりに、カスタムメッセージを使用できます。指定する方法はいくつかあります。If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages.

バリデーターにカスタムメッセージを渡すPassing Custom Messages Into Validator

$messages = array(
	'required' => 'The :attribute field is required.',
);

$validator = Validator::make($input, $rules, $messages);

注目:attributeプレースホルダーはバリデーション中のフィールド名に置き換わります。バリデーションメッセージごとに別のプレースホルダーも使用できます。Note: The :attribute place-holder will be replaced by the actual name of the field under validation. You may also utilize other place-holders in validation messages.

他のバリデーションのプレースホルダーOther Validation Place-Holders

$messages = array(
	'same'    => 'The :attribute and :other must match.',
	'size'    => 'The :attribute must be exactly :size.',
	'between' => 'The :attribute must be 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 messages only for a specific field:

$messages = array(
	'email.required' => 'We need to know your e-mail address!',
);

言語ファイルにカスタムメッセージを指定するSpecifying Custom Messages In Language Files

場合により、Validatorに直接カスタムメッセージを渡すよりは、言語ファイルに指定したい場合もあるでしょう。そのためには、resources/lang/xx/validation.php言語ファイルのcustom配列にメッセージを追加してください。In some cases, you may wish to specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.

'custom' => array(
	'email' => array(
		'required' => 'We need to know your e-mail address!',
	),
),

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

カスタムバリデーションルールを登録するRegistering A Custom Validation Rule

Laravelは多彩な役に立つバリデーションを提供していますが、自分だけの特別なバリデーションを使用したい場合もあるでしょう。カスタムバリデーションルールを登録する一つの方法は、validator::extendメソッドを使用する方法です。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 the Validator::extend method:

Validator::extend('foo', function($attribute, $value, $parameters)
{
	return $value == 'foo';
});

カスタムバリデーターの無名関数は3つの引数を取ります。$attributeはバリデーションをしているフィールド、$valueはその値、$parametersはルールに渡された引数です。The custom validator Closure receives three arguments: the name of the $attribute being validated, the $value of the attribute, and an array of $parameters passed to the rule.

クロージャーの代わりにextendメソッドへクラスとメソッドを渡すこともできます。You may also pass a class and method to the extend method instead of a Closure:

Validator::extend('foo', 'FooValidator@validate');

カスタムルールにエラーメッセージも定義する必要があります。同時にエラーメッセージを定義することも、また言語ファイルにエントリーを追加することも可能です。Note that you will also need to define an error message for your custom rules. You can do so either using an inline custom message array or by adding an entry in the validation language file.

Validatorクラスを拡張するExtending The Validator Class

Validatorに無名関数のコールバックを追加するより、Validatorクラスそのものを拡張したい場合もあるでしょう。そうであれば、Illuminate\Validation\Validatorを拡張して自分のValidatorを書くこともできます。そのクラスにvalidateのプレフィックスをつけたバリデーションメソッドを追加してください。Instead of using Closure callbacks to extend the Validator, you may also extend the Validator class itself. To do so, write a Validator class that extends Illuminate\Validation\Validator. You may add validation methods to the class by prefixing them with validate:

<?php

class CustomValidator extends Illuminate\Validation\Validator {

	public function validateFoo($attribute, $value, $parameters)
	{
		return $value == 'foo';
	}

}

カスタムバリデーターリゾルバーを登録するRegistering A Custom Validator Resolver

次にカスタムバリデーター拡張を登録する必要があります。Next, you need to register your custom Validator extension:

Validator::resolver(function($translator, $data, $rules, $messages)
{
	return new CustomValidator($translator, $data, $rules, $messages);
});

カスタムバリデーションルールを作成する場合、時々エラーメッセージ中で置き換えるカスタムプレースホルダーを定義する必要が起きます。今まで説明したカスタムバリデーションの作成を行い、それからバリデーターにreplaceXXX関数を追加してください。When creating a custom validation rule, you may sometimes need to define custom place-holder replacements for error messages. You may do so by creating a custom Validator as described above, and adding a replaceXXX function to the validator.

protected function replaceFoo($message, $attribute, $rule, $parameters)
{
	return str_replace(':foo', $parameters[0], $message);
}

Validatorクラスを拡張せずに、カスタムメッセージへ置き換えたい場合は、Validator::replacerメソッドを使用できます。If you would like to add a custom message "replacer" without extending the Validator class, you may use the Validator::replacer method:

Validator::replacer('rule', function($message, $attribute, $rule, $parameters)
{
	//
});

章選択

Artisan CLI

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作