laravel 验证器使用

1.前后端不分离 (form表单提交)

 

控制器定义验证规则

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class LoginController
{
    /**
     * @param Request $request
     * 登录
     */
    public function login(Request $request)
    {
        $post['name'] = $request->input('name');
        $post['password'] = $request->input('password');

        $messages = [
            'name.required' => '请输入账号',
            'name.max' => '账号错误',
            'password.required' => '请输入密码',
            'password.max' => '密码错误',
            ];

        Validator::make($post, [
            'name' => 'required|max:20',
            'password' => 'required|max:30',
        ],$messages)->validate();

    }
}

 

前端

@error('name')
   <span class="invalid-feedback" role="alert">
       <strong>{{ $message }}</strong>
   </span>
@enderror

 

 

 

2.前后端分离

 

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class LoginController
{
    /**
     * @param Request $request
     * 登录
     */
    public function login(Request $request)
    {
        $post['name'] = $request->input('name');
        $post['password'] = $request->input('password');

        $messages = [
            'name.required' => '请输入账号',
            'name.max' => '账号错误',
            'password.required' => '请输入密码',
            'password.max' => '密码错误',
            ];

        $validator = Validator::make($post, [
            'name' => 'required|max:20',
            'password' => 'required|max:30',
        ],$messages);
        
        if ($validator->fails()){
            //返回错误信息
            //{
            //    "name": [
            //        "账号错误"
            //    ],
            //    "password": [
            //        "密码错误"
            //    ]
            //}
            var_dump($validator->errors()->messages());
        }

    }
}

 

posted @ 2020-07-13 12:17  钧一  阅读(1018)  评论(0编辑  收藏  举报