0

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?

3
  • 2
    what error you are getting.? Commented Jan 29, 2020 at 8:01
  • There's no error but the data isnt being processed inside the jQuery validate function. Commented Jan 29, 2020 at 8:14
  • please read jQuery Validation doc 1st Commented Jan 29, 2020 at 8:27

1 Answer 1

1

The rules option of the jQuery validate plugin uses element names, not ids. From the docs (emphasis mine):

rules ...

Type: Object Key/value pairs defining custom rules. Key is the name of an element (or a group of checkboxes/radio buttons), value is an object consisting of rule/parameter pairs or a plain String.

Your HTML inputs have no name attributes, only ids. So the validation is not tied to those inputs at all, and nothing is validated. Just add a name attribute to both inputs:

<input name="new_password" id="new_password" ...>
<input name="old_password" id="old_password" ...>

Incidentally without names, your fields would not be sent to your backend, so the backend Laravel validation would also fail!

Working - much simplified - JSFiddle.

Side note: you have a typo - <lebel> should be <label>.

Another side note: please consider trying to create a minimal, complete, and verifiable example. The majority of the time I spent on this question was simply removing stuff from your code - CSS classes, empty <h6>, all the error* stuff, messages ... not only is it easier for others to read and understand your problem, but by reducing things to the bare minimum to reproduce the problem you are much more likely to find the answer yourself without needing help!

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your reply and feedback. Yes, I do agree that it looks cluttered. Please pardon me for that. I will check this out and let you know!
No prob - as I said, it can help you and others find the problem quicker and easier when you pare things down as far as you can and still reproduce the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.