laravel笔记-验证

这篇博客详细介绍了 Laravel 中的数据验证,包括在控制器和请求中进行验证,处理错误信息,自定义错误格式,使用Validator门面,以及如何显示验证错误。还提到了AJAX请求中的验证规则和响应处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

laravel笔记-验证

写在前面

时间可贵,善用目录↑

学习Laravel的笔记,仅仅是作为laravel文档笔记,目的是强化对文档的理解,质量不高。


什么是验证?

你前端不能一直只是页面跳来跳去吧,得有个表单啥的像后台提交点数据吧。

然后就是在哪验证,这个有很多种:
控制器中 $this->validate()
请求中rules()
在任何地方Validator::make()


如何验证

在控制器中

Laravel 的控制器基类使用ValidatesRequests trait,该trait提供了便利的方法通过各种功能强大的验证规则来验证输入的 HTTP 请求。

下面为一段控制器中的代码(一个方法):

/**
 * 存储博客文章
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request){
    //验证请求,按顺序验证
    $this->validate($request, [
        // '参数名' => '规则1|规则2'
        'title' => 'required|unique:posts|max:255',
        //注意这里的bail,存在这个规则的验证向不通过时直接跳出不继续验证
        'body' => 'bail|required',
        //这里是对数组的验证,使用'.'解析
        'author.name' => 'required',
        'author.description' => 'required',

    ]);

    // 验证通过,存储到数据库...
}

验证后如果出现错误,laravel会重定向到上一个页面并将错误信息全部存在session中。

处理错误信息

自定义错误格式

自定义保存在session中的验证错误信息的格式,需要在控制器基类中重写formatValidationErrors方法

不要忘了在该控制器类的顶部导入Illuminate\Contracts\Validation\Validator类

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;

abstract class Controller extends BaseController{
    use DispatchesJobs, ValidatesRequests;

    /**
     * {@inheritdoc}
     */
    protected function formatValidationErrors(Validator $validator)
    {
        return $validator->errors()->all();
    }
}

在请求中

在一些情况下,我们可能需要定义一个’表单请求’来处理某些特定的请求。

使用验证

我们可以通过如下Artisan命令来自定义一个请求:

php artisan make:request StoreBlogPost

生成的类位于app/Http/Requests目录下,接下来我们添加少许验证规则到rules方法:

/**
 * 获取应用到请求的验证规则
 *
 * @return array
 */
public function rules(){
    return [
        //规则同上文~
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

这样,只要在控制器中使用该类型的请求就可以自动验证了:

/**
 * 存储输入的博客文章
 *
 * @param  StoreBlogPostRequest  $request
 * @return Response
 */
public function store(StoreBlogPost $request){
    // The incoming request is valid...
}

值得一说的是,在Request类中还有一个方法authorize(),这个方法被用来验证检查认证用户是否有资格更新指定资源。

例如,用户要编辑一篇文章的评论,要验证评论的归属:

/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    //这里Comment为评论的模型
    $comment = Comment::find($this->route('comment'));
    //判断是否有资格
    return $comment && $this->user()->can('update', $comment);
}
Route::post('comment/{comment}');

处理错误信息

自定义错误格式

重写请求基类(App\Http\Requests\Request)中的formatErrors方法即可.

不要忘记在文件顶部导入Illuminate\Contracts\Validation\Validator类

/**
 * {@inheritdoc}
 */
protected function formatErrors(Validator $validator){
    return $validator->errors()->all();
}

自定义错误消息

重写messages方法自定义表单请求使用的错误消息.

/**
 * Get the error messages for the defined validation rules.
 *
 * @return array
 */
public function messages(){
    return [
        'title.required' => 'A title is required',
        'body.required'  => 'A message is required',
    ];
}

使用Validator门面

使用验证

使用Validator门面的make方法,我们可以更加随意的验证信息。

比如:

/**
     * 存储新的博客文章
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        //第一个参数是需要验证的数据,第二个参数是要应用到数据上的验证规则。
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);
        //满足$input->games不小于100时验证reason
        $v->sometimes('reason', 'required|max:500', function($input) {
            return $input->games >= 100;
        });
        //如果希望在验证完成后添加回调函数,使用after方法,如下
        $validator->after(function($validator) {
            if ($this->somethingElseIsInvalid()) {
                $validator->errors()->add('field', 'Something is wrong with this field!');
            }
        });

        //判断验证结果
        if ($validator->fails()) {
            //重定向
            return redirect('post/create')
                    //将错误数据一次性存放到session,$errors会被填充
                    //withErrors()接收一个验证器、或一个MessageBag,或PHP数组
                    //如果一个页面有多个表单,可以传入第二个参数命名MessageBag
                    ->withErrors($validator, 'login')
                    ->withInput();
        }

        // 存储博客文章...
    }

在view中我们可以这样获得:

{{ $errors->login->first('email') }}

如果希望自动重定向:

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validate();

处理错误信息

调用Validator实例上的errors方法之后,将会获取一个Illuminate\Support\MessageBag实例,该实例中包含了多种处理错误信息的便利方法。在所有视图中默认有效的$errors变量也是一个MessageBag实例。

获取

//获取某字段的第一条错误信息
$messages = $validator->errors();
//获取某字段的所有错误信息
foreach ($messages->get('email') as $message) {
    //
}
//获取数组字段的所有错误信息
foreach ($errors->get('attachments.*') as $message) {
    //
}
//获取所有字段的所有错误信息
foreach ($messages->all() as $message) {
    //
}

//判断消息中是否存在某字段的错误信息
if ($messages->has('email')) {
    //
}
//获取指定格式的错误信息
echo $messages->first('email', '<p>:message</p>');
//获取指定格式的所有错误信息
foreach ($messages->all('<li>:message</li>') as $message) {
    //
}

自定义错误信息

make方法的第三个参数可以自定义错误信息

$messages = [
    //注意:':attribute'占位符会被验证的字段名替换。
    'required' => 'The :attribute field is required.',
    //对指定字段的指定错误设置信息
    'email.required' => 'We need to know your e-mail address!',
];

$validator = Validator::make($input, $rules, $messages);

如何显示

在视图中,我们可以使用$errors变量来获得错误信息:

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

$errors变量是的一个Illuminate\Support\MessageBag实例,会通过web中间件组中的Illuminate\View\Middleware\ShareErrorsFromSession中间件绑定到视图~


关于AJAX

在AJAX请求中如果验证失败,Laravel不会生成重定向响应。取而代之的,Laravel生成一个包含验证错误信息的JSON响应。该JSON响应会带上一个HTTP状态码422。

验证规则

验证方式意义
accepted必须是yes、on、1或true,这在“同意服务协议”时很有用。
active_url该字段必须是一个基于PHP函数checkdnsrr 的有效URL
after:date给定日期(字段)后的一个值,日期将会通过PHP函数strtotime传递
alpha该字段必须是字母
alpha_dash该字段可以包含字母和数字,以及破折号和下划线
alpha_num该字段必须是字母或数字
array该字段必须是PHP数组
before:date指定日期之前的一个数值,该日期将会传递给PHP strtotime函数。
between:min,max给定的最小值和最大值之间,字符串、数值和文件
boolean必须可以被转化为boolean,接收true, false, 1,0, “1”, 和 “0”等
confirmed必须有一个匹配字段foo_confirmation
date验证字段必须是一个基于PHP strtotime函数的有效日期
date_format:format匹配指定格式
different:field验证字段必须是一个和指定字段不同的值
digits:value验证字段必须是数字且长度为value指定的值
digits_between:min,max验证字段数值长度必须介于最小值和最大值之间
dimensions图片尺寸’dimensions:min_width=100,min_height=200’
distinct验证字段不能包含重复值
email验证字段必须是格式化的电子邮件地址
exists:table,column验证字段必须存在于指定数据表
file该验证字段必须是上传成功的文件
filled该验证字段如果存在则不能为空
image验证文件必须是图片(jpeg、png、bmp、gif或者svg)
in:foo,bar…验证字段值必须在给定的列表中
in_array:另一个字段验证字段必须在另一个字段中存在
integer验证字段必须是整型
ip验证字段必须是IP地址
JSON验证字段必须是有效的JSON字符串
max:value验证字段必须小于等于最大值
mimetypes:text/plain…验证文件必须匹配给定的MIME文件类型之一
mimes:foo,bar,…验证文件的MIMIE类型必须是该规则列出的扩展类型中的一个
min:value验证字段的最小值
nullable验证字段必须为null
not_in:foo,bar,验证字段值不在给定列表中
numeric验证字段必须是数值
present验证字段必须出现在输入数据中但可以为空
regex:pattern验证字段必须匹配给定正则表达式
required输入字段值不能为空
required_if:anotherfield,value另一个字段等于指定值value时是必须的
required_unless:anotherfield,value除了另一字段为value,验证字段不能空
required_with:foo,bar只有在任一其它指定字段存在的话才是必须的
required_with_all:foo,bar只有在所有指定字段存在的情况下才是必须的
required_without:foo,bar只有当任一指定字段不存在的情况下才是必须的
required_without_all:当所有指定字段不存在的情况下才是必须的
same:field给定字段和验证字段必须匹配
size:value和给定值value相匹配的尺寸
string验证字段必须是字符串
timezone基于PHP函数timezone_identifiers_list的有效时区标识
unique:table,column,except,idColumn给定数据表上必须是唯一的
url验证字段必须是基于PHP函数filter_var过滤的的有效URL

老眼昏花了已经…….

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值