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 手机归属地查询 api
Feb 08 PHP
发款php蜘蛛统计插件只要有mysql就可用
Oct 12 PHP
ThinkPHP采用模块和操作分析
Apr 18 PHP
php debug 安装技巧
Apr 30 PHP
PHP正确解析UTF-8字符串技巧应用
Nov 07 PHP
destoon出现验证码不显示时的紧急处理方法
Aug 22 PHP
php判断类是否存在函数class_exists用法分析
Nov 14 PHP
php上传文件问题汇总
Jan 30 PHP
Zend Framework教程之模型Model用法简单实例
Mar 04 PHP
PHP-FPM运行状态的实时查看及监控详解
Nov 18 PHP
php将html转为图片的实现方法
May 19 PHP
tp5修改(实现即点即改)
Oct 18 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导入Excel到MySQL的方法
2011/04/23 PHP
PHP的Laravel框架中使用AdminLTE模板来编写网站后台界面
2016/03/21 PHP
一款js和css代码压缩工具[附JAVA环境配置方法]
2010/04/16 Javascript
纯js实现背景图片切换效果代码
2010/11/14 Javascript
window.navigate 与 window.location.href 的使用区别介绍
2013/09/21 Javascript
无闪烁更新网页内容JS实现
2013/12/19 Javascript
js 点击页面其他地方关闭弹出层(示例代码)
2013/12/24 Javascript
JavaScript+CSS控制打印格式示例介绍
2014/01/07 Javascript
javascript获取当前鼠标坐标的方法
2015/01/10 Javascript
jQuery实现提示密码强度的代码
2015/07/15 Javascript
JavaScript中this的9种应用场景及三种复合应用场景
2015/09/12 Javascript
教大家轻松制作Bootstrap漂亮表格(table)
2016/12/13 Javascript
ES6教程之for循环和Map,Set用法分析
2017/04/10 Javascript
浅谈vue项目如何打包扔向服务器
2018/05/08 Javascript
vue.js使用v-pre与v-html输出HTML操作示例
2018/07/07 Javascript
JavaScript基于对象方法实现数组去重及排序操作示例
2018/07/10 Javascript
详解如何用webpack4从零开始构建react开发环境
2019/01/27 Javascript
基于JS开发微信网页录音功能的实例代码
2019/04/30 Javascript
javascript面向对象三大特征之多态实例详解
2019/07/24 Javascript
[00:08]DOTA2勇士令状等级奖励“天外飞星”
2019/05/24 DOTA
Python读写Redis数据库操作示例
2014/03/18 Python
python Django模板的使用方法
2016/01/14 Python
Python中import导入上一级目录模块及循环import问题的解决
2016/06/04 Python
Django框架的中的setting.py文件说明详解
2018/10/15 Python
详解Python3除法之真除法、截断除法和下取整对比
2019/05/23 Python
Python实现列表中非负数保留,负数转化为指定的数值方式
2020/06/04 Python
pytorch 计算ConvTranspose1d输出特征大小方式
2020/06/23 Python
python 星号(*)的多种用途
2020/09/21 Python
html5定位获取当前位置并在百度地图上显示
2014/08/22 HTML / CSS
Qoo10马来西亚:全球时尚和引领潮流的购物市场
2016/08/25 全球购物
家乐福台湾线上购物网:Carrefour台湾
2020/09/15 全球购物
必须要使用游标的SQL语句有那些
2012/05/07 面试题
毕业求职自荐信格式是什么
2013/11/19 职场文书
应届毕业生通用的自荐书范文
2014/02/07 职场文书
python中os.path.join()函数实例用法
2021/05/26 Python
React forwardRef的使用方法及注意点
2021/06/13 Javascript