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 相关文章推荐
php 遍历数据表数据并列表横向排列的代码
Sep 05 PHP
php 各种应用乱码问题的解决方法
May 09 PHP
PHP 多维数组排序(usort,uasort)
Jun 30 PHP
php中http_build_query 的一个问题
Mar 25 PHP
PHP URL路由类实例
Nov 12 PHP
php使用smtp发送支持附件的邮件示例
Apr 13 PHP
PHP中使用xmlreader读取xml数据示例
Dec 29 PHP
php上传图片并压缩的实现方法
Dec 22 PHP
浅谈php中的循环while、do...while、for、foreach四种循环
Nov 05 PHP
php中加密解密DES类的简单使用方法示例
Mar 26 PHP
php中array_fill函数的实例用法
Mar 02 PHP
阿里云服务器搭建Php+Apache运行环境的详细过程
May 15 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
Yii2框架中日志的使用方法分析
2017/05/22 PHP
一个关于jqGrid使用的小例子(行按钮)
2011/11/04 Javascript
密码强度检测效果实现原理与代码
2013/01/04 Javascript
JQuery页面图片切换和新闻列表滚动效果的具体实现
2013/09/26 Javascript
js数组方法扩展实现数组统计函数
2014/04/09 Javascript
JavaScript获取function所有参数名的方法
2015/10/30 Javascript
JavaScript中Number对象的toFixed() 方法详解
2016/09/02 Javascript
NodeJS遍历文件生产文件列表功能示例
2017/01/22 NodeJs
react-router JS 控制路由跳转实例
2017/06/15 Javascript
jQuery开源组件BootstrapValidator使用详解
2017/06/29 jQuery
Node.js 的模块知识汇总
2017/08/16 Javascript
jQuery 获取除某指定对象外的其他对象 ( :not() 与.not())
2018/10/10 jQuery
vue input实现点击按钮文字增删功能示例
2019/01/29 Javascript
详解Vue项目引入CreateJS的方法(亲测可用)
2019/05/30 Javascript
小试小程序云开发(小结)
2019/06/06 Javascript
layui复选框限制选择个数的方法
2019/09/18 Javascript
vue分页插件的使用方法
2019/12/25 Javascript
小程序实现长按保存图片的方法
2019/12/31 Javascript
Python实现学生成绩管理系统
2020/04/05 Python
python 借助numpy保存数据为csv格式的实现方法
2018/07/04 Python
python判断文件是否存在,不存在就创建一个的实例
2019/02/18 Python
python获取地震信息 微信实时推送
2019/06/18 Python
python实现动态数组的示例代码
2019/07/15 Python
使用pymysql查询数据库,把结果保存为列表并获取指定元素下标实例
2020/05/15 Python
处理textarea中的换行和空格
2019/12/12 HTML / CSS
乔丹诺(Giordano)酒庄德国官网:找到最好的意大利葡萄酒
2017/12/28 全球购物
孤独星球出版物:Lonely Planet Publications
2018/03/17 全球购物
公司董事长职责
2013/12/12 职场文书
如何写一份好的自荐信
2014/01/02 职场文书
七一党建活动方案
2014/01/28 职场文书
法律专业自荐信
2014/06/03 职场文书
2014国庆节幼儿园亲子活动方案
2014/09/16 职场文书
2014年人大工作总结
2014/12/10 职场文书
2014年校长工作总结
2014/12/11 职场文书
机关工会工作总结2015
2015/05/26 职场文书
电力安全教育培训心得体会
2016/01/11 职场文书