laravel unique验证、确认密码confirmed验证以及密码修改验证的方法


Posted in PHP onOctober 16, 2019

confirmed

验证字段必须有一个匹配字段 foo_confirmation,例如,如果验证字段是 password,必须输入一个与之匹配的 password_confirmation 字段。

same:field

给定字段和验证字段必须匹配

protected $fillable = ['name', 'password'];
 
 public static $rules = [
  'name'   => 'required|unique:managers',
  'password' => 'required|confirmed',
  'password_confirmation' => 'required|same:password'
 ];
 
 public static function error_message() 
 {
  return [
   'name.required' => __('tyvalidation.name'),
   'name.unique' => __('tyvalidation.unique'),
   'password.required' => __('tyvalidation.password'),
   'password.confirmed' => __('tyvalidation.confirmed'),
  ];
 }
 
 public function setPasswordAttribute($value)
 {
  $this->attributes['password'] = Hash::make($value);
 }

经验证,上面的验证方式在update的时候会出问题,修改的时候会验证unique,导致不能保存,所以需要修改下。

官网说:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the |character to delimit the rules:

重要的2句话是: 

有时,您可能希望在唯一检查期间忽略给定的ID。

当然,您需要验证电子邮件地址是否唯一。但是,如果用户仅更改名称字段而不更改电子邮件字段,则不希望抛出验证错误,因为用户已经是电子邮件地址的所有者,为了指示验证者忽略用户的ID,我们将使用Rule该类来流畅地定义规则。

use Illuminate\Validation\Rule;
 
Validator::make($data, [
  'email' => [
    'required',
    Rule::unique('users')->ignore($user->id),
  ],
]);

所以修改为

'name'   => [
     'required',
     Rule::unique('managers')->ignore($id),
    ],

在更新密码时,我们需要验证旧的密码是否正确,那我们需要使用自定义验证。

Using Closures

If you only need the functionality of a custom rule once throughout your application, you may use a Closure instead of a rule object. The Closure receives the attribute's name, the attribute's value, and a $fail callback that should be called if validation fails:

Closure接收属性的名称,属性的值以及$fail在验证失败时应调用的回调。

$validator = Validator::make($request->all(), [
  'title' => [
    'required',
    'max:255',
    function($attribute, $value, $fail) {
      if ($value === 'foo') {
        return $fail($attribute.' is invalid.');
      }
    },
  ],
]);

所以密码是否正确可以这样验证

'old_password' => [
     'required',
     function($attribute, $value, $fail) use ($manager) 
     {
      if (!Hash::check($value, $manager->password)) 
      {
       return $fail(__('tyvalidation.old_password'));
      }
     },
    ],

所有代码如下:

create.html

<div class="form-group">
      <label>{!! __('tycms.name') !!}</label>
      <div class="input-group">
       <div class="input-group-prepend">
        <span class="input-group-text change-bg">T</span>
       </div>
       <input type="text" class="form-control is-invalid" name="name" value="" placeholder="{!! __('tycms.name') !!}" required />
       @foreach ($errors->get('name') as $message) 
       <div class="invalid-feedback">
        {{ $message }}
       </div>
       @endforeach
      </div>
     </div>
     <div class="form-group">
      <label>{!! __('tycms.password') !!}</label>
      <div class="input-group">
       <div class="input-group-prepend">
        <span class="input-group-text change-bg">T</span>
       </div>
       <input type="password" class="form-control is-invalid" name="password" value="" placeholder="{!! __('tycms.password') !!}" required />
       @foreach ($errors->get('password') as $message) 
       <div class="invalid-feedback">
        {{ $message }}
       </div>
       @endforeach
      </div>
     </div>
     <div class="form-group">
      <label>{!! __('tycms.confirm_password') !!}</label>
      <div class="input-group">
       <div class="input-group-prepend">
        <span class="input-group-text change-bg">T</span>
       </div>
       <input type="password" class="form-control is-invalid" name="password_confirmation" value="" placeholder="{!! __('tycms.confirm_password') !!}" required />
       @foreach ($errors->get('password') as $message) 
       <div class="invalid-feedback">
        {{ $message }}
       </div>
       @endforeach
      </div>
     </div>

store

$input_all = $request->all();
   $validator = Validator::make($input_all, Manager::rules(), Manager::error_message());
   if ($validator->fails()) 
   {
     return redirect()
           ->action($this->class_basename . '@create')
           ->withErrors($validator)
           ->withInput();
   }
   $model = Manager::create($input_all);

edit.html

<div class="form-group">
      <label>{!! __('tycms.name') !!}</label>
      <div class="input-group">
       <div class="input-group-prepend">
        <span class="input-group-text change-bg">T</span>
       </div>
       <input type="text" class="form-control is-invalid" name="name" value="{{ $model->name }}" readonly="readonly" placeholder="{!! __('tycms.name') !!}" required />
       @foreach ($errors->get('name') as $message) 
       <div class="invalid-feedback">
        {{ $message }}
       </div>
       @endforeach
      </div>
     </div>
     <div class="form-group">
      <label>{!! __('tycms.old_password') !!}</label>
      <div class="input-group">
       <div class="input-group-prepend">
        <span class="input-group-text change-bg">T</span>
       </div>
       <input type="password" class="form-control is-invalid" name="old_password" value="" placeholder="{!! __('tycms.old_password') !!}" required />
       @foreach ($errors->get('old_password') as $message) 
       <div class="invalid-feedback">
        {{ $message }}
       </div>
       @endforeach
      </div>
     </div>
     <div class="form-group">
      <label>{!! __('tycms.password') !!}</label>
      <div class="input-group">
       <div class="input-group-prepend">
        <span class="input-group-text change-bg">T</span>
       </div>
       <input type="password" class="form-control is-invalid" name="password" value="" placeholder="{!! __('tycms.password') !!}" required />
       @foreach ($errors->get('password') as $message) 
       <div class="invalid-feedback">
        {{ $message }}
       </div>
       @endforeach
      </div>
     </div>
     <div class="form-group">
      <label>{!! __('tycms.confirm_password') !!}</label>
      <div class="input-group">
       <div class="input-group-prepend">
        <span class="input-group-text change-bg">T</span>
       </div>
       <input type="password" class="form-control is-invalid" name="password_confirmation" value="" placeholder="{!! __('tycms.confirm_password') !!}" required />
       @foreach ($errors->get('password') as $message) 
       <div class="invalid-feedback">
        {{ $message }}
       </div>
       @endforeach
      </div>
     </div>

update

$input_all = $request->all();
   $model = $this->findById($id);
 
   $validator = Validator::make($input_all, Manager::rules($id, $model), Manager::error_message());
   if ($validator->fails()) 
   {
     return redirect()
           ->action($this->class_basename . '@edit', ['id' => $id])
           ->withErrors($validator)
           ->withInput();
   }
   $model->fill($input_all);
   $model->save();

Models\Manager

protected $table = 'managers';
 
 protected $fillable = ['name', 'password'];
 
 /*public static $rules = [
  'name'   => 'required|unique:managers',
  'password' => 'required|confirmed',
  'password_confirmation' => 'required|same:password'
 ];*/
 
 public static function rules ($id = null, $manager = null) 
 {
  if (empty($id))
  {
   $rules = [
    'name'   => 'required|unique:managers',
    'password' => 'required|confirmed',
    'password_confirmation' => 'required|same:password'
   ];
  } else 
  {
   $rules = [
    'name'   => [
     'required',
     Rule::unique('managers')->ignore($id),
    ],
    'old_password' => [
     'required',
     function($attribute, $value, $fail) use ($manager) 
     {
      if (!Hash::check($value, $manager->password)) 
      {
       return $fail(__('tyvalidation.old_password'));
      }
     },
    ],
    'password' => 'required|confirmed',
    'password_confirmation' => 'required|same:password'
   ];
  }
  return $rules;
 }
 
 public static function error_message() 
 {
  return [
   'name.required' => __('tyvalidation.name'),
   'name.unique' => __('tyvalidation.unique'),
   'password.required' => __('tyvalidation.password'),
   'password.confirmed' => __('tyvalidation.confirmed'),
  ];
 }
 
 public function setPasswordAttribute($value)
 {
  $this->attributes['password'] = Hash::make($value);
 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
第十三节 对象串行化 [13]
Oct 09 PHP
PHP4 与 MySQL 交互使用
Oct 09 PHP
一个PHP模板,主要想体现一下思路
Dec 25 PHP
php用正则表达式匹配URL的简单方法
Nov 12 PHP
使用PHP和HTML5 FormData实现无刷新文件上传教程
Sep 06 PHP
使用PHP实现阻止用户上传成人照片或者裸照
Dec 25 PHP
php给图片加文字水印
Jul 31 PHP
thinkPHP+PHPExcel实现读取文件日期的方法(含时分秒)
Jul 07 PHP
微信支付开发交易通知实例
Jul 12 PHP
php获取当前月与上个月月初及月末时间戳的方法
Dec 05 PHP
PHP使用glob方法遍历文件夹下所有文件的实例
Oct 17 PHP
php中目录操作opendir()、readdir()及scandir()用法示例
Jun 08 PHP
解决thinkPHP 5 nginx 部署时,只跳转首页的问题
Oct 16 #PHP
详解将数据从Laravel传送到vue的四种方式
Oct 16 #PHP
漂亮的thinkphp 跳转页封装示例
Oct 16 #PHP
Thinkphp页面跳转设置跳转等待时间的操作
Oct 16 #PHP
解决thinkphp5未定义变量会抛出异常,页面错误,请稍后再试的问题
Oct 16 #PHP
thinkphp5使html5实现动态跳转的例子
Oct 16 #PHP
Thinkphp5 如何隐藏入口文件index.php(URL重写)
Oct 16 #PHP
You might like
php中实现记住密码自动登录的代码
2011/03/02 PHP
详解HTTP Cookie状态管理机制
2016/01/14 PHP
zend framework中使用memcache的方法
2016/03/04 PHP
JavaScript 中的事件教程
2007/04/05 Javascript
javascript脚本编程解决考试分数统计问题
2008/10/18 Javascript
ASP.NET MVC中EasyUI的datagrid跨域调用实现代码
2012/03/14 Javascript
JS 数字转换研究总结
2013/12/26 Javascript
Js操作树节点自动折叠展开的几种方法
2014/05/05 Javascript
Node.js异步I/O学习笔记
2014/11/04 Javascript
JS实现的3D拖拽翻页效果代码
2015/10/31 Javascript
AngularJS实现表单手动验证和表单自动验证
2015/12/09 Javascript
jQuery+canvas实现简单的球体斜抛及颜色动态变换效果
2016/01/28 Javascript
Angular-Touch库用法示例
2016/12/22 Javascript
vue中使用微信公众号js-sdk踩坑记录
2019/03/29 Javascript
基于layui轮播图满屏是高度自适应的解决方法
2019/09/16 Javascript
JavaScript的变量声明与声明提前用法实例分析
2019/11/26 Javascript
微信小程序学习总结(五)常见问题实例小结
2020/06/04 Javascript
[01:59]游戏“zheng”当时试玩会
2019/08/21 DOTA
python使用ctypes模块调用windowsapi获取系统版本示例
2014/04/17 Python
详解Python中的元组与逻辑运算符
2015/10/13 Python
Python常见排序操作示例【字典、列表、指定元素等】
2018/08/15 Python
详解如何将python3.6软件的py文件打包成exe程序
2018/10/09 Python
python批量爬取下载抖音视频
2019/06/17 Python
python常用函数与用法示例
2019/07/02 Python
css3 position fixed固定居中问题解决方案
2014/08/19 HTML / CSS
canvas学习笔记之绘制简单路径
2019/01/28 HTML / CSS
女子锻炼服装和瑜伽服装:Splits59
2019/03/04 全球购物
NHL官方在线商店:Shop.NHL.com
2020/05/01 全球购物
师范学院教师自荐书
2014/01/31 职场文书
大四学生找工作的自荐信
2014/03/27 职场文书
食品安全承诺书
2014/05/22 职场文书
三关爱志愿服务活动方案
2014/08/17 职场文书
小学英语课教学反思
2016/02/15 职场文书
人事行政部各岗位职责说明书!
2019/07/15 职场文书
解析目标检测之IoU
2021/06/26 Python
python垃圾回收机制原理分析
2022/04/13 Python