I have a form that allows a user to update his/her current password. The data passes through a Validate plugin in Jquery i.e with rules and messages. And I am using AJAX to pass the data to my controller, include validation for it and update the current password to the new one inputted. However, the jquery validate plugin does not work for me.
Please view the code:
template.blade.php:
<form id="update_password_form">
@csrf
<div class="single_form_item ">
<lebel class="default_lebel" for="password">Password</lebel><br>
<input class="default_input" id="new_password" type="password" value="" placeholder="New password">
<h6></h6>
<input class="default_input ml-15-fix" id="old_password" type="password" value="" placeholder="Old password">
<h6></h6>
</div>
<button class="btn_small btn_br_20 float-right" type ='submit'> Save </button>
</form>
myfile.js:
$("#update_password_form").validate({
errorClass: "invalid form-error",
errorElement: 'div',
errorPlacement: function(error, element) {
error.appendTo(element.parent().find('h6'));
},
rules: {
new_password:{
required: true,
minlength:5,
},
old_password:{
required: true,
minlength:5,
},
},
messages: {
new_password: {
required: "Enter password",
minlength: "Password must be at least 5 characters long"
},
old_password: {
required: "Enter password",
minlength: "Password must be at least 5 characters long"
},
},
submitHandler: function (form) {
var data = $("#update_password_form").serialize();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type:"POST",
data:data,
url: base_url+'/password',
dataType:"json",
success:function(data){
if(data.success){
console.log('SUCCESS');
}else{
console.log('ERROR');
}
}
});
}
});
MyController.php:
public function password(Request $request)
{
$rules = [
'new_password'=>'required',
'old_password' => 'required',
];
$customMessages = [
'new_password.required' => 'The password field is required.',
'old_password.required' => 'The old password field is required.',
];
if ($validator->fails()){
$response['message'] = $validator->errors()->all()[0];
$response['success'] = false;
return $response;
} else {
$user_id = Auth::user()->id;
$new_password = $request->new_password;
$old_password = $request->old_password;
$check_pass = User::where('id', $user_id)->first();
if (Hash::check($old_password, $check_pass->password)) {
$hashed_pswd = Hash::make($new_password);
User::where('id', $user_id)
->update(['password' => $hashed_pswd]);
$response['status'] = true;
$response['message'] = 'Updated your password!';
return $response;
}
else {
$response['status'] = false;
$response['message'] = 'Incorrect password.';
return $response;
}
}
}
Why isn't my data getting validated through the Jquery plugin?