laravel密码并确认密码无法正常工作

时间:2020-11-10 06:42:14

标签: laravel

我是laravel中的验证规则,查看所有验证规则,但如果我在两个字段中都输入相同的密码,则密码和确认密码不匹配。我在两个字段中都使用了自定义消息,这是我做错了什么。

刀片:

<div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                      <label for="inputPassword">Password</label>
                      <input type="password" class="form-control" id="inputPassword" placeholder="Enter Password" name="password">
                       <span class="text-danger">{{ $errors->first('password') }}</span>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                      <label for="inputCPassword">Password</label>
                      <input type="password" class="form-control" id="inputCPassword" placeholder="Enter Confirm Password" name="cpassword">
                      </div>
                </div>
            </div>
            

控制器:

public function store(Request $req)
    {
        $user=new Users;
        $mytime = Carbon::now();
        $user->updated_at=$mytime->toDateTimeString();
        $user->created_at=$mytime->toDateTimeString(); 
        $user->name=$req->input('name');
        $user->email=$req->input('email');
        $user->password=$req->input('password');
        $user->cpassword=$req->input('cpassword');
        $user->mobile_number=$req->input('mobile_number');

        $messages = [
               'password.confirmed' => 'Your passwords were mismatched',
               'cpassword.min' => 'Your password must be at least 4 characters'
                    ];

        $rules=[
        'name' => 'required',
        'email' => 'required|email|unique:table_users',
        'mobile_number' => 'required|unique:table_users',
        'password' => 'min:4|confirmed',
        'cpassword'   => 'min:4|confirmed',
        ];

        $this->validate($req, $rules, $messages);

        $user->save();

        return redirect('login')->with('success',"You have successfully submitted data & now you can login"); 

1 个答案:

答案 0 :(得分:2)

Laravel验证'password' => 'min:4|confirmed',

这意味着它将寻找此字段以匹配password_confirmation

示例

'foo' => 'min:4|confirmed',

它将查找输入文件name="foo_confirmation",因此此处foo应该与foo_confirmation字段匹配

参考链接 https://laravel.com/docs/8.x/validation#rule-confirmed


如果您需要更改

$rules = [
    'name' => 'required',
    'email' => 'required|email|unique:table_users',
    'mobile_number' => 'required|unique:table_users',
    'password' => 'min:4|confirmed',
];

删除cpassword

<input type="password" class="form-control" id="inputCPassword" placeholder="Enter Confirm Password" name="cpassword">

<input type="password" class="form-control" id="inputCPassword" placeholder="Enter Confirm Password" name="password_confirmation">

cpassword命名为password_confirmation