最适合入门的Laravel中级教程(三)表单验证
做开发有个原则是永远不能信任用户输入的数据;
即便前端已经做了验证;
在后端 php 也必须要再次验证;
laravel 为表单验证提供了强大且简单的方案;
创建示例路由:
routes/web.php
Route::prefix('validation')->group(function () {
Route::get('create', 'ValidationController@create');
Route::post('store', 'ValidationController@store');
Route::get('edit', 'ValidationController@edit');
Route::post('update', 'ValidationController@update');
});
创建控制器
php artisan make:controller ValidationController --resource
app/Http/Controllers/ValidationController.php
public function create()
{
return view('validation.create');
}
创建视图;
这里直接把官方自带的注册页面复制过来做示例了;
为了方便验证后台我把 html 标签的验证删除了;
并增加了一个 tag 选项;
resources/views/validation/create.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">注册</div>
<div class="panel-body">
<form class="form-horizontal" method="POST" action="{{ url('validation/store') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('tag') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">标签</label>
<div class="col-md-6">
<select class="form-control" name="tag">
<option value="">请选择标签</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
@if ($errors->has('tag'))
<span class="help-block">
<strong>{{ $errors->first('tag') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">用户名</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" autofocus>
@if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">邮箱</label>
<div class="col-md-6">
<input id="text" type="email" class="form-control" name="email" value="{{ old('email') }}">
@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">密码</label>
<div class="col-md-6">
<input id="password" type="text" class="form-control" name="password">
@if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<label for="password-confirm" class="col-md-4 control-label">确认密码</label>
<div class="col-md-6">
<input id="password-confirm" type="text" class="form-control" name="password_confirmation">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
注册
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
现在到了后台验证的时候了;
laravel 可以直接在控制器中直接写验证逻辑;
不过我建议单独创建验证类;
以控制器名为目录;
以方法名为文件名;
这里为 store 方法创建一个验证类;
php artisan make:request Validation/Store
执行命令会生成 app/Http/Requests/Validation/Store.php 文件;
<?php
namespace App\Http\Requests\Validation;
use Illuminate\Foundation\Http\FormRequest;
class Store extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}
默认生成的验证类中只有 authorize
和 rules
方法; authorize()
主要用于验证权限;
如上面代码所示默认直接返回 fase
意味着所有的请求都不能通过验证;
假如说只允许 user_id
为 1 的用户执行 store
方法;
我们可以这样改写 验证类的 authorize()
;
public function authorize()
{
return Auth::id() === 1 ? true : false;
}
还有很多时候我们并不需要验证身份;
那直接返回 true
即可;
public function authorize()
{
return true;
}
另外就是 rules
方法;
根据前端页面增加以下验证;
public function rules()
{
return [
'tag' => 'required',
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
];
}
这些规则都可以在文档中找到表单验证 ;
要使用这个验证器也很简单;
只需要在 store
方法的类型约束中使用 Store
即可;
use App\Http\Requests\Validation\Store;
public function store(Store $request)
{
dump($request->all());
}
增加验证后我们访问 /validation/create
页面点击注册按钮;

当点击注册按钮的时候会刷新下页面并显示红色的提示信息;
但是提示信息全是英文;
要想显示中文我们可以翻译 resources/lang/en/validation.php 文件中的内容;
另外 overtrue 有一个翻译好的扩展包可以供我们使用 laravel-lang ;
composer require "overtrue/laravel-lang:~3.0"
在 config/app.php 文件中把 Illuminate\Translation\TranslationServiceProvider::class,
替换成 Overtrue\LaravelLang\TranslationServiceProvider::class,
;
再次点击注册按钮就可以看到中文的提示信息了;

但是我们可以看到 tag
并没有被翻译出来;
像这类非通用性的字段;
我们可以在验证类 app/Http/Requests/Validation/Store.php 中定义 attributes
方法;
在方法中以键值对的方式翻译字段;
public function attributes()
{
return [
'tag' => '标签',
];
}
再次刷新页面;

标签是翻译过来了;
但是我明明一个下拉选择标签但是提示却是输入类型的不能为空;
叔可以忍婶婶是忍不了了;
像这类情况我们还可以在验证类 app/Http/Requests/Validation/Store.php 中定义一个 messages
方法;
在方法中以字段拼接验证类型来翻译字段和验证类型的错误信息;
public function messages()
{
return [
'tag.required' => '必须选择标签',
];
}

泼飞克特;
终于如愿以偿;
验证失败的信息都是在 session 中存储;
可以使用 session()
获取到失败的信息;

另外 laravel 还在 app/Http/Kernel.php 中注册了 ShareErrorsFromSession
中间件;
它的作用是可以让我们在视图文件直接使用储存了错误信息的变量 $errors
;
最适合入门的Laravel中级教程(三)表单验证的更多相关文章
- 最适合入门的Laravel中级教程(一)
Laravel 是一个全栈框架: 我们使用 Laravel 开发业务常见有 3 个方向: 前端页面和后端逻辑混合的应用 主要是面向对 SEO 有需求的项目: 比如说新闻资讯博客文章等: 一般在控制器中 ...
- 最适合入门的Laravel中级教程(二)用户认证
之前的初级教程主要是学习简单的增删改查: 接着的中级教程的目标是在初级教程的基础上能写出更复杂更健壮的程序: 我们先来学习 laravel 的用户认证功能: 在现代网站中基本都有用户系统: 而我们每开 ...
- 最适合入门的Laravel中级教程(四)前端开发
Laravel 使用 npm 安装前端依赖: npm 是一个类似 composer 的工具: 用于管理前端的各种依赖包: 在使用之前需要先安装 node : Windows 下可以在官网下载安装: h ...
- [AngularJS] AngularJS系列(3) 中级篇之表单验证
目录 基本验证 验证插件messages 自定义验证 基本验证 <form name="form" novalidate ng-app> <span>{{f ...
- Laravel在进行表单验证时,错误信息未返回
马上要毕业了,找了现在的这家公司,压力不大,自己也比较喜欢,唯一的遗憾就是手机号莫得换了(找不到换的借口). 进入正题: 之前自己的博客(http://lxiaoke.cn)是用ThinkPHP开发的 ...
- Laravel教程 七:表单验证 Validation
Laravel教程 七:表单验证 Validation 此文章为原创文章,未经同意,禁止转载. Laravel Form 终于要更新这个Laravel系列教程的第七篇了,期间去写了一点其他的东西. 就 ...
- 无废话ExtJs 入门教程四[表单:FormPanel]
无废话ExtJs 入门教程四[表单:FormPanel] extjs技术交流,欢迎加群(201926085) 继上一节内容,我们在窗体里加了个表单.如下所示代码区的第28行位置,items:form. ...
- 【干货】Laravel --Validate (表单验证) 使用实例
前言 : Laravel 提供了多种方法来验证应用输入数据.默认情况下,Laravel 的控制器基类使用ValidatesRequests trait,该trait提供了便利的方法通过各种功能强大的验 ...
- SpringMVC.入门篇《二》form表单
SpringMVC.入门篇<二>form表单 项目工程结构: 在<springmvc入门篇一.HelloWorld>基础上继续添加代码,新增:FormController.ja ...
随机推荐
- 虚拟机U盘挂载
虚拟机中U盘挂载 一.连接U盘 虚拟机中 虚拟机→可移动设备→Syntek USB......(U盘的名称)→连接: 二.查看U盘的UUID “lsblk -f”: UUID为 35E6-9 ...
- Python 管道
from multiprocessing import Process,Pipe def f1(conn): from_zhujincheng = conn.recv() print("我是 ...
- MySQL设置空密码
因为刚安装的时候,MySQL强制设置密码,但是我需要设置MySQL为空密码 语句: ';
- s21day06 python笔记
s21day06 python笔记 一.昨日内容回顾及补充 回顾 补充 列表独有功能 reverse:反转 v = [1,2,3,4,5] v.reverse() #[5,4,3,2,1] sort: ...
- spring jpa + mybatis快速开始:
springmvc开始搭建 源码地址 https://gitee.com/flydb/spingjpamy pom: <packaging>war</packaging> &l ...
- 记录一次mysql查询速度慢造成CPU使用率很高情况
1.某日zabbix告警,某台机器CPU使用率过高. 查看慢查询日志,看到很多sql语句都超过10秒 把sql语句拿出来放在查询窗口执行.前面加上explain就可以查看详细查询信息 playcode ...
- C166 -MDH
Writing a C logic for moving MDH register contents after MUL instruction http://www.keil.com/forum ...
- Http原理与实践
Http原理 一.使用Http协议最简单的例子 1.输入URL打开网页 2.AJAX获取数据 3.img标签加载图片 二.Cache-Control 1.public.private 2.must-r ...
- shell 生成MAC地址
# cat /dev/urandom |od -x |awk '{print $2,$3,$4}' |head -n 1 |sed -e 's/[[:space:]]//g' -e 's/\(..\) ...
- PCL中Sample_consensus分割支持的几何模型
随机采样一致分割法,从点云中分割出线.面等几何元素 #include <pcl/sample_consensus/method_types.h> #include <pcl/samp ...