表单数组输入验证功能实现


Laravel 5.2 新增表单数组输入验证,听起来很懵?下面我们以一个具体例子来演示这一功能。

首先在routes.php定义相应路由:

  1. Route::get('form','TestController@form');
  2. Route::post('form/validate','TestController@validate');

然后使用Artisan命令创建对应控制器:

  1. php artisan make:controller TestController

编辑生成的TestController.php文件内容如下:

  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6.  
  7. use App\Http\Requests;
  8. use App\Http\Controllers\Controller;
  9.  
  10. class TestController extends Controller
  11. {
  12. public function form()
  13. {
  14. return view('test.form');
  15. }
  16.  
  17. public function validate(Requests\FormRequest $request)
  18. {
  19. return 'success';
  20. }
  21. }

接下来创建表单视图文件resources/views/test/form.blade.php,编辑form.blade.php文件内容如下:

  1. @extends('layouts.app')
  2.  
  3. @section('content')
  4. <div class="container">
  5. <div class="row">
  6. @if (count($errors) > 0)
  7. <div class="alert alert-danger">
  8. <ul>
  9. @foreach ($errors->all() as $error)
  10. <li>{{ $error }}</li>
  11. @endforeach
  12. </ul>
  13. </div>
  14. @endif
  15. <form action="{{url('form/validate')}}" method="POST">
  16. {!! csrf_field() !!}
  17. <label>Company Name</label>
  18. <input type="text" name="name">
  19.  
  20. <h3>Employees</h3>
  21. <div class="add-employee">
  22. <label>Employee Name</label>
  23. <input type="text" name="employee[1][name]">
  24. <label>Employee Title</label>
  25. <input type="text" name="employee[1][title]">
  26. </div>
  27. <div class="add-employee">
  28. <label>Employee Name</label>
  29. <input type="text" name="employee[2][name]">
  30. <label>Employee Title</label>
  31. <input type="text" name="employee[2][title]">
  32. </div>
  33.  
  34. <input type="submit">
  35. </form>
  36. </div>
  37. </div>
  38. @endsection

我们在表单中定义了数组输入字段employee[][name]employee[][title],以便同时输入多个员工姓名和职位。

此外,注意到我们在控制器TestControllervalidate方法中注入了FormRequest请求类,我们将在这个类中实现表单输入验证逻辑,下面我们使用Artisan命令生成这个请求类:

  1. php artisan make:request FormRequest

这样会在app/Http/Requests目录下生成FormRequest.php,编辑该文件内容如下:

  1. <?php
  2.  
  3. namespace App\Http\Requests;
  4.  
  5. use App\Http\Requests\Request;
  6.  
  7. class FormRequest extends Request
  8. {
  9. /**
  10. * Determine if the user is authorized to make this request.
  11. *
  12. * @return bool
  13. */
  14. public function authorize()
  15. {
  16. return true;
  17. }
  18.  
  19. /**
  20. * Get the validation rules that apply to the request.
  21. *
  22. * @return array
  23. */
  24. public function rules()
  25. {
  26. return [
  27. 'name'=>'required|max:100',
  28. 'employee.*.name'=>'required|max:100',
  29. 'employee.*.title'=>'required|max:100'
  30. ];
  31. }
  32. }

至此,我们已经完成代码编写工作,下面我们来测试数组输入验证,在浏览器中访问http://laravel.app/form,页面显示如下:

Laravel表单数组输入验证

我们接下来输入一些表单数据:

Laravel表单数组输入验证

最后,点击“提交”按钮,显示验证错误提示信息:

Laravel表单数组输入验证