0

I stuck a little bit with my form and I do not know how to solve my current issue. I made a form so that a user can change his password. I want to validate the form with jQuery. Therefore I am using the plugin from http://jqueryvalidation.org/!

My update function and therefore the form is working. Also if I enter for example a password with 3 letters I get an error message so jQuery validation is working too.

My problem is now, that I can submit the form EVEN if there are some issues like the passwords are not equal or the password is too short. The form gets submitted everytime when I click the submit button.

I am not good a jQuery but I read something about submitHandler and I tried it (see my code below) but it is not working.

Can someone tell me what my code should look like so that the form is only submitted if it passes the jQuery validation? I do not want to change my php code if possible because I am using functions for inserting and updating my database. Would be great if someone can help me.

<?php

    $sessioninfo=getSessionInfo($sid);
    $gl_userid=$sessioninfo["pers_id"][0];
    $userdata=getUserInfo($gl_userid,0);



    if (isset ($_POST['submit'])) {

        $content=array("password"=>crypt($pwdnew1));
        updateUserInfo($gl_userid,$content);

        if(updateUserInfo($gl_userid, $content)==TRUE){
        $msg_success ="Your password was changed successfully!";
        } else {
        $msg_error ="ERROR! Your password could not be changed caused by an error! Please check and try again...";
        }

    }

    print "<div class='widget-box'>";
    print "<div class='widget-header'>";
    print "<h5 class='widget-title'>You can change your Password here</h5>";
    print "</div>";
    print "<div class='widget-body'>";
    print "<div class='widget-main'>";
    print "<form class='form-horizontal' name='changepwd' id='changepwd' action='./index.php' method='post'>\n";
    print "<input type='hidden' name='func' value='chpwd'>\n";
    print "<input type='hidden' name='sid' value='".$sid."'>\n";
    print "<div class='form-group'>";
    print "<label for='inputName' class='col-sm-4 control-label'>Your ID:</label>";
    print "<div class='col-sm-6'>";
    print "<input type='text' class='form-control' name='yourid' id='yourid' placeholder='Your ID' value='$gl_userid' readonly>";
    print "</div>";
    print "</div>";
    print "<div class='form-group'>";
    print "<label for='inputOldPassword' class='col-sm-4 control-label'>Your old Password:</label>";
    print "<div class='col-sm-6'>";
    print "<input type='password' class='form-control' name='pwdold' id='pwdold' placeholder='Enter your current Password'>";
    print "</div>";
    print "</div>";
    print "<div class='form-group'>";
    print "<label for='inputNewPassword' class='col-sm-4 control-label'>New Password:</label>";
    print "<div class='col-sm-6'>";
    print "<input type='password' class='form-control' name='pwdnew1' id='pwdnew1' placeholder='Enter your new Password'>";
    print "</div>";
    print "</div>";
    print "<div class='form-group'>";
    print "<label for='inputRepeadPassword' class='col-sm-4 control-label'>Repead your new Password:</label>";
    print "<div class='col-sm-6'>";
    print "<input type='password' class='form-control' name='pwdnew2' id='pwdnew2' placeholder='Enter your new Password'>";
    print "</div>";
    print "</div>";
    print "<div class='form-group'>";
    print "<div class='col-sm-offset-5 col-sm-4'>";
    print "<button type='submit' name='submit' value='submit' class='btn btn-warning btn-lg btn-block'>Change Password</button>";
    print "</div>";
    print "</div>";
    print "</form>";

    if(isset($msg_success)){ echo '<div class="alert alert-success"> <a href="#" class="close" data-dismiss="alert">&times;</a>'.$msg_success.' </div>'; }
    if(isset($msg_error)){ echo '<div class="alert alert-info"> <a href="#" class="close" data-dismiss="alert">&times;</a>'.$msg_error.' </div>'; }

    print "</div>";
    print "</div>";
    print "</div>";

    print "<script src='./bootstrap/assets/js/jquery.validate.js'></script>";
    print "<script src='./bootstrap/assets/js/additional-methods.js'></script>";

?>

        <script type="text/javascript">
            $('#changepwd').validate({
                    errorElement: 'div',
                    errorClass: 'help-block',
                    focusInvalid: false,
                    ignore: "",
                    rules: {
                        pwdold: {
                            required: true,
                            pwdold:true
                        },
                        pwdnew1: {
                            required: true,
                            minlength: 5
                        },
                        pwdnew2: {
                            required: true,
                            minlength: 5,
                            equalTo: "#pwdnew1"
                        }

                    },

                    highlight: function (e) {
                        $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
                    },

                    success: function (e) {
                        $(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
                        $(e).remove();
                    },

                    errorPlacement: function (error, element) {
                        if(element.is('input[type=checkbox]') || element.is('input[type=radio]')) {
                            var controls = element.closest('div[class*="col-"]');
                            if(controls.find(':checkbox,:radio').length > 1) controls.append(error);
                            else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
                        }
                        else if(element.is('.select2')) {
                            error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
                        }
                        else if(element.is('.chosen-select')) {
                            error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
                        }
                        else error.insertAfter(element.parent());
                    },

                    submitHandler: function (form) {
                    $.post("index.php", $("#changepwd").serialize());
                    },

                    invalidHandler: function (form) {
                    }
                });
        </script>
3
  • You should validate the password on the server. It's possible for users to skip past any jQuery you write. Though it's a nicety to also validate it with jQuery. Commented Sep 10, 2015 at 17:37
  • Thanks for the info but that is not a solution for my current problem! I still need someone who can help me and tell me what I have to do so that the form is not submitted if the jquery validation false! Commented Sep 10, 2015 at 17:44
  • Just tested your code - it appears to work just fine. I tweaked a few things: added in the jQuery core (but if some validation works, I can't see this being the issue). Removed "<script src='./bootstrap/assets/js/additional-methods.js'></script>" as I don't have that file. Removed pwdold:true, I imagine that's in the file I removed. Commented Sep 10, 2015 at 18:09

1 Answer 1

1

It looks like it is the following line:

                    pwdold: {
                        required: true,
                        pwdold:true
                    },

If you make that:

                    pwdold: "required",

It should work. I don't know what you were trying to do with that line pwdold:true.

Now, that being said, let's take the time to talk about a few things.

  • First, in addition to client-side validation, you must have server-side validation. I can disable javascript in my browser and turn off all client-side validation. So you'll need to duplicate those rules in php. Alternatively, you could set up server-side validation on form submit which responds with what's wrong, and only have validation in one place.

  • Second, you are doing HTML all wrong. PHP is, on some level, a templating language. You can close your php tags, write html, and open new php tags when you need more php. You may even want to look into a more explicit templating system like twig or blade.

  • Third, if this is in anyway meant to be more than a simple experimental exercise, and it is something you expect people to use, I highly recommend you learn and use a framework. My personal preference is Laravel. They have a lot of good documentation and resources. If you want to roll your own, The PHP League has some good packages to assist in doing that.

  • Fourth, check out phptherightway. It is an incredibly useful intro to building applications with PHP, and can save you a lot of headache in the future.

  • Finally, remember that you should always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.

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

4 Comments

I mostly agree, but I'd recommend that beginners in PHP/programming in general avoid any of the frameworks and focus instead on things only in the PHP core. While they're super helpful for experienced devs, I can see how they can be too overwhelming for someone just getting started.
@HPierce I agree only if they are coming from another language. Unfortunately, the PHP core can be so crazy and wtf-ish that I would prefer new developers to learn a good framework so they can pick up better practices and consistent standards. This goes over a lot of the problems with the PHP core, and I don't want an inexperienced programmer to think those things are ok.
@MirroredFate thank you so much for your help! I changed my code and now it seems as the jquery validation is working. Problem now is that if I enter everything correctly and click the submit button, it is not working anymore. Form is not submitted. I did nothing else except changing the pwold: "required". Any idea?
@MirroredFate ok it seems as the password is changed if I click on submit button but there is not success message. Any idea why?

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.