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初学者头疼问题总结
Oct 09 PHP
用PHP进行MySQL删除记录操作代码
Jun 07 PHP
php explode函数实例代码
Feb 27 PHP
PHP保留两位小数并且四舍五入及不四舍五入的方法
Sep 22 PHP
PHP批量检测并去除文件BOM头代码实例
May 08 PHP
Centos下升级php5.2到php5.4全记录(编译安装)
Apr 03 PHP
PHP实现批量删除(封装)
Apr 28 PHP
PHP中使用jQuery+Ajax实现分页查询多功能操作(示例讲解)
Sep 17 PHP
php字符串过滤strip_tags()函数用法实例分析
Jun 24 PHP
详细分析PHP 命名空间(namespace)
Jun 30 PHP
Docker 安装 PHP并与Nginx的部署实例讲解
Feb 27 PHP
php TP5框架生成二维码链接
Apr 01 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/09/20 PHP
php中base64_decode与base64_encode加密解密函数实例
2014/11/24 PHP
详解WordPress开发中get_header()获取头部函数的用法
2016/01/08 PHP
PHP面向对象之工作单元(实例讲解)
2017/06/26 PHP
javascript 事件绑定问题
2011/01/01 Javascript
jquery 查找select ,并触发事件的实现代码
2011/03/30 Javascript
输入框的字数时时统计—关于 onpropertychange 和 oninput 使用
2011/10/21 Javascript
jQuery 联动日历实现代码
2012/05/31 Javascript
jQuery操作select的实例代码
2012/06/14 Javascript
jquery动态增加text元素以及删除文本内容实例代码
2013/07/01 Javascript
alert中断settimeout计时功能
2013/07/26 Javascript
详解 javascript中offsetleft属性的用法
2015/11/11 Javascript
使用vue编写一个点击数字计时小游戏
2016/08/31 Javascript
javascript实现根据汉字获取简拼
2016/09/25 Javascript
原生JS实现圣旨卷轴展开效果
2017/03/06 Javascript
JS完成画圆圈的小球
2017/03/07 Javascript
微信小程序媒体组件详解(视频,音乐,图片)
2017/09/19 Javascript
基于bootstrap写的一点localStorage本地储存
2017/11/21 Javascript
详解nodejs通过响应回写的方式渲染页面资源
2018/04/07 NodeJs
vue将单页面改造成多页面应用的方法
2018/11/25 Javascript
微信 jssdk 签名错误invalid signature的解决方法
2019/01/14 Javascript
跟混乱的页面弹窗说再见
2019/04/11 Javascript
layui原生表单验证的实例
2019/09/09 Javascript
微信小程序跳转到其他网页(外部链接)的实现方法
2019/09/20 Javascript
Python实现的简单万年历例子分享
2014/04/25 Python
使用python编写android截屏脚本双击运行即可
2014/07/21 Python
python实现文件快照加密保护的方法
2015/06/30 Python
Python将图片转换为字符画的方法
2020/06/16 Python
使用TensorFlow实现SVM
2018/09/06 Python
大学活动邀请函
2014/01/28 职场文书
护士求职信
2014/07/05 职场文书
工作失职造成投诉的检讨书范文
2014/10/05 职场文书
招商银行工作证明
2015/06/17 职场文书
简历中的自我评价怎么写呢?
2019/04/30 职场文书
创业计划书之酒厂
2019/10/14 职场文书
Angular性能优化之第三方组件和懒加载技术
2021/05/10 Javascript