基本验证

使用Validator::make($data, $rules)验证,第一个参数为需验证的数据,第二个参数为每个字段的验证规则

  1. Route::post('/registration',function()
  2. {
  3. $data =Input::all();
  4. // Build the validation constraint set.
  5. $rules = array(
  6. 'username'=>'alpha_num'
  7. );
  8. // Create a new validator instance.
  9. $validator =Validator::make($data, $rules);
  10. });

如需多个验证规则,使用|隔开

  1. $rules = array('username'=>'alpha_num|min:3');

或是使用数组

  1. $rules = array('username'=> array('alpha_num','min:3'));

创建完一个验证,使用$validator->passes()$validator->fails()执行验证,判断验证是否通过

  1. if($validator->passes()){
  2. // Normally we would do something with the data.
  3. return'Data was saved.';
  4. }

具体验证规则参考官方API

错误消息

获取错误消息列表

  1. $errors = $validator->messages();

获取一个域的第一个消息

  1. $errors->first('email');

获取一个域的全部消息

  1. foreach($errors->get('email')as $message)
  2. {
  3. //
  4. }

获取全部域的全部错误消息

  1. foreach($errors->all()as $message)
  2. {
  3. //
  4. }

检查一个域是否存在消息

  1. $errors->has('email')

向视图反馈消息

  1. returnRedirect::to('/')->withErrors($validator);

在视图中使用

  1. <ulclass="errors">
  2. @foreach($errors->all() as $message)
  3. <li></li>
  4. @endforeach
  5. </ul>

以某种格式获取消息

  1. @foreach($errors->all('<li>:message</li>')as $message)
  2. @endforeach

或是

  1. $errors->first('username',':message'<span class="error">:message</span>)

自定义验证规则

  1. Validator::extend('awesome',function($field, $value, $params)
  2. {
  3. return $value =='awesome';
  4. });

定制的验证器接受三个参数:待验证属性的名字、待验证属性的值以及传递给这个规则的参数。传递一个类的函数到 extend 函数,而不是使用闭包:

  1. Validator::extend('awesome','CustomValidation@awesome');

自定义错误消息

传递定制消息到验证器

  1. // Build the custom messages array.
  2. $messages = array(
  3. 'min'=>'Yo dawg, this field aint long enough.'
  4. );
  5. // Create a new validator instance.
  6. $validator =Validator::make($data, $rules, $messages);

验证占位符

  1. $messages = array(
  2. 'same'=>'The :attribute and :other must match.',
  3. 'size'=>'The :attribute must be exactly :size.',
  4. 'between'=>'The :attribute must be between :min - :max.',
  5. 'in'=>'The :attribute must be one of the following types: :values',
  6. );

对一个指定的域指定定制的错误消息

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

结束