2

I have the following form which is added to a page via ajax

<script>
    $(document).ready(function() {

        jQuery.validator.setDefaults({
            errorPlacement: function(error, element) {
                 error.appendTo('#invalid_' + element.attr('id'));
            }
        });

        var validator = $("#login_form").validate({
            rules: {
                user_email: {
                  required: true,
                  email: true
                },
                password: {
                    required: true
                }
            }
        });
    });

</script>

<form id="login_form">
<center><br/><br/><br/>
    <div class="login_div">
        <center><h3>Log In</h3>
        <table align="center" width="400px">
            <tr><td class="input_td">Email:</td><td class="textfield_td"><input type="text" class="textfield" id="user_email" name="user_email"/></td></tr>
            <tr><td colspan="2" id="invalid_user_email"></td></tr>
            <tr><td class="input_td">Password:</td><td class="textfield_td"><input type="password" class="textfield" id="password" name="password"/></td></tr>
            <tr><td colspan="2" id="invalid_password"></td></tr>
            <tr><td colspan="2" class="error_text" id="login_error"></td></tr>
        </table>
        <input  type="button" onclick="check_login();" value="Log In"/></center>
    </div>
</center>
</form>

The check_login method has this structure: if($("#login_form").valid()) {do something} else {return;}

When i click the Log in button the first time the form validates correctly e.g. If fields are missing or an invalid email is supplied then the appropriate error messages are shown. However if i then click the log in button again the valid() method returns true even if fields are missing or there is an invalid email and no error messages are shown.

thanks for any light you can shed on this

EDIT: This solution appears to work where login is the id of the button

$("#login").click(function() {

    validator.resetForm();
    if(validator.form()) {
         alert('valid');

    }
    else {
        return;
    }


});
Sparky
  • 98,165
  • 25
  • 199
  • 285
user2274191
  • 843
  • 2
  • 14
  • 24
  • Can you please check what exactly is value of `$("#login_form").valid()` inside `check_login` method? – PrimosK May 09 '13 at 13:59
  • Can you post your check_login() function too, besides the pseudo code thing – Ejaz May 09 '13 at 14:03
  • Your `check_login()` function is like having a custom validator inside of the validator plugin. That's pointless when the jQuery Validate will do all of this automatically. You just have to leverage the built-in callback options. – Sparky May 09 '13 at 15:35
  • As a side-note, you should really examine the validity of your HTML. `
    ` has been deprecated for a very long time, as only one example.
    – Sparky May 09 '13 at 16:04
  • hi sparky - what do you mean by levarage the built in call back options. Is the solution/edit i posted redundant? I only did it this way as i'm not using forms and submit buttons, rather posting back with ajax. I havent programmed for many years and have never used jquery before so i could be doing it all totally wrong – user2274191 May 09 '13 at 16:11
  • @user2274191, see my answer which properly leverages the `submmitHandler` callback function. – Sparky May 09 '13 at 16:19

5 Answers5

2

You do not need if($("#login_form").valid()) {do something} because the plugin's built-in submitHandler already follows this exact same logic.

As per documentation, the submitHandler is:

"Callback for handling the actual submit when the form is valid."

(it's also the correct place to put any ajax required for form submission.)

DEMO: http://jsfiddle.net/uxzH6/

$(document).ready(function () {

    $('#login_form').validate({
        rules: {
            user_email: {
                required: true,
                email: true
            },
            password: {
                required: true
            }
        },
        submitHandler: function (form) {
            // any ajax would go here
            alert('valid form submitted'); // for demo
            return false;
        }
    });

});

Your button:

<input type="button" onclick="check_login();" value="Log In"/>

You are using jQuery so any inline JavaScript is rendered ugly and superfluous. onclick can easily be replaced with a jQuery click handler. HOWEVER, in this case, you do not need any click handlers at all since the built-in submitHandler already captures the click event. You just need to change your input type to submit.

<input type="submit" value="Log In"/>

Quote OP:

"I have the following form which is added to a page via ajax"

<script>
    $(document).ready(function() {
    ...

The DOM ready handler function, $(document).ready(), only fires when the DOM is fully constructed on a normal page load. It will do nothing when code is loaded into a page with ajax(). You have not shown the code that writes this into your page, but if you want to initialize the Validate plugin, you would need to move your $('#login_form').validate({... code into whatever code writes your form's HTML.

$.ajax({
    // code to load the form's HTML into the page
    // initialize plugin here after ajax is complete
    complete: function() {
        $('#login_form').validate({ ... });
    }
    ....

And finally, please validate the HTML of your form. You're using deprecated code such as <center></center> and <table align=.

Sparky
  • 98,165
  • 25
  • 199
  • 285
1

You should do

if (validator.form()){}

instead of

$("#login_form").valid().
Rajeev Nair
  • 759
  • 8
  • 20
  • hi - this does not work for me...function check_login() { alert('here'); alert(validator.form()); alert('here again'); the second alert is never called – user2274191 May 09 '13 at 14:32
  • There is nothing wrong with `$("#login_form").valid()`. You should read the documentation for the `valid()` method: http://docs.jquery.com/Plugins/Validation/valid – Sparky May 09 '13 at 15:17
1

While you're using the jQuery validate plugin, a good practice is to handle the form submission inside the validator code as well. jQuery validate plugin has a submitHandler callback just for that event, i.e., when your form has been validated and it is about to be submitted. You can put your custom logic inside this callback or call your check_login() inside this callback as well. returning false from this callback will prevent the form submit. Check the code below

       var validator = $("#login_form").validate({
           rules: {
              user_email: {
                 required: true,
                 email: true
              },
              password: {
                 required: true
              }
           },
           /* following callback will be called when the form has passed validation*/
           submitHandler: function () {
              //call your custom code here and return true/false to submit/cancel form
              check_login();

              //in-case you've missed a return statement in your custom function
              return false;
           }
    });

And remove check_login() from the button

<input type="submit" value="Log In" />

Also note that I've changed the type of button from button to submit.

P.S. for astute readers: I KNOW that there might be other ways of solving this issue, as always are for all issues.

Ejaz
  • 8,719
  • 3
  • 34
  • 49
0

try calling validator.resetForm() or possibly $('#login_form').data('validator').resetForm(). Here's a great example How to clear Jquery validation error messages?

You want the resetForm() method:

var validator = $("#login_form").validate(
   ...
   ...
);
// to reset
$("#some_element_id").click(function() {
    validator.resetForm();
});
Community
  • 1
  • 1
carrabino
  • 1,742
  • 1
  • 14
  • 17
  • calling the reset form fixed the problem for me. i tried to upvote you but was not allowed. Thanks for taking the time to reply. – user2274191 May 09 '13 at 14:37
  • hi again - i thought your solution worked but on further investigation it isn't. I tried this function – user2274191 May 09 '13 at 15:09
  • just curious, did you double check that the validator.resetForm() was indeed called? (e.g. adding console.log("form was reset"); in the click event above? – carrabino May 09 '13 at 16:14
0

This is my form:

<form method="post" class="form" name="form_destination" id="form_destination">
  <label style="margin-bottom: 10px" class="white block text-left">Enter country code followed by phone number then click Search <span class="badge badge-primary pointer tax-help" data-container="body" data-toggle="popover" data-placement="top" data-content="Enter the number you wish to call, recharge or send sms to. You must first enter the country code followed by the phone number, then press Search." data-original-title="" title="" aria-describedby="popover">?</span></label>
       <div class="input-group">
          <input type="tel" class="form-control text-center" placeholder="Type number" style="font-weight: 400;font-size: x-large;" name="destination" id="destination">
          <span class="input-group-addon pointer btn-naranja" id="btn_buscar"><i class="fa fa-search"></i> Search</span>
       </div>
</form> 

JavaScript solution:

$('#form_destination').on('submit', function(e) {
    e.preventDefault();
    $('#destination').focus();
    $('#form_destination').validate({
        rules: {
            destination: {
                required: true,
                minlength: 7,
                digits: true,
            }
        }, 
        messages: {
            destination: {
                required: "Please enter a phone number",
                minlength: "Please write at least 7 phone numbers",
                digits: "Please enter the phone number",
            }
        }, 
        submitHandler(form) {
            /* AJAX JQuery */
            /* your code */
        }
    });
});

$('#btn_buscar').on('click', function(event) {
    $('#form_destination').submit();
    $('#form_destination').submit();
    /* this my solution */
});
Daniel
  • 2,355
  • 9
  • 23
  • 30