Laravel 4之验证
基本验证
使用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';
});
定制的验证器接受三个参数:待验证属性的名字、待验证属性的值以及传递给这个规则的参数。传递一个类的函数到 extend 函数,而不是使用闭包:
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!',
);