码迷,mamicode.com
首页 > 其他好文 > 详细

laravel 验证器使用

时间:2020-07-13 13:27:53      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:strong   date   验证   规则   size   pac   ade   pos   pre   

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": [
            //        "密码错误"
            //    ]
            //}
            return $validator->errors();
        }

    }
}

 

laravel 验证器使用

标签:strong   date   验证   规则   size   pac   ade   pos   pre   

原文地址:https://www.cnblogs.com/junyi-bk/p/13292552.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!