Laravel 4の検証
9971 ワード
Laravel 4の検証
http://dingjiannan.com/2013/laravel-validation/
基本的な検証
エラーメッセージ
エラーメッセージのリストを取得
http://dingjiannan.com/2013/laravel-validation/
基本的な検証
Validator::make($data, $rules)
を用いて検証し、第一パラメータは検証が必要なデータであり、第二パラメータは各フィールドの検証ルールである。Route::post('/registration',function()
{
$data =Input::all();
// Build the validation constraint set.
$rules = array(
'username'=>'alpha_num'
);
// Create a new validator instance.
$validator =Validator::make($data, $rules);
});
複数の検証ルールが必要な場合は、|
を用いて隔てる。$rules = array('username'=>'alpha_num|min:3');
または行列を使用します$rules = array('username'=> array('alpha_num','min:3'));
検証を作成し終わったら、$validator->passes()
または$validator->fails()
を使って検証を実行し、検証が通過したかどうかを判断する。if($validator->passes()){
// Normally we would do something with the data.
return'Data was saved.';
}
具体的な検証ルールは、公式APIを参照してください。エラーメッセージ
エラーメッセージのリストを取得
$errors = $validator->messages();
ドメインの最初のメッセージを取得します。$errors->first('email');
ドメインのすべてのメッセージを取得します。foreach($errors->get('email')as $message)
{
//
}
すべてのドメインのエラーメッセージを取得します。foreach($errors->all()as $message)
{
//
}
メッセージがあるかどうかチェックします。$errors->has('email')
メッセージをビューにフィードバックするreturnRedirect::to('/')->withErrors($validator);
ビューで使用<ulclass="errors">
@foreach($errors->all() as $message)
<li></li>
@endforeach
</ul>
メッセージを何らかの形式で取得します。@foreach($errors->all('<li>:message</li>')as $message)
@endforeach
$errors->first('username',':message',<span class="error">:message</span>)
カスタム ルールValidator::extend('awesome',function($field, $value, $params)
{
return $value =='awesome';
});
カスタマイズされたベリファイアは、 の の 、 の の 、およびこのルールに すパラメータの3つを け れる。 じたパケットを するのではなく、クラスの をexted に します。Validator::extend('awesome','CustomValidation@awesome');
カスタムエラーメッセージ
オーダーメードメッセージをベリファイアに る// Build the custom messages array.
$messages = array(
'min'=>'Yo dawg, this field aint long enough.'
);
// Create a new validator instance.
$validator =Validator::make($data, $rules, $messages);
プレースホルダ$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',
);
されたドメインにカスタマイズされたエラーメッセージを します。$messages = array(
'email.required'=>'We need to know your e-mail address!',
);