最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery Validate + AJAX username availability check: How to marry them? - Stack Overflow

programmeradmin3浏览0评论

UPDATE


Thanks to charlietfl's ments and suggestions (and, at one point ire, lol - apologies for my faux pas), I've finally got the system checking from within Validate, and the form submission is halted when the email is sent. So I guess my question is answered, but if you'll all bear with me for one more moment, there's one last finishing touch that I could use your help with...

In my original vision, in addition to triggering a proper "Email already exists" error, I also populated a second element with some HTML that more pletely explained the situation to the user and provided a link to a login form. This second element appeared and disappeared depending on the status of the field.

Is there a way to use the messages/remote section to do this as well?

Here what I have:

$(document).ready(function(){
$("#signup").validate({
    errorElement: "span",
    errorPlacement: function(error, element) {
        error.appendTo(element.prev());
        //element.prev().replaceWith(error);
    },
    rules: {
        "email": {
            required: true,
            email:true,
            remote: {
                url: "/ajax/emailcheck.php",
                type: "post",
            },
        },
        "password": {
            required: true,
            minlength: 8,
        },
        "password-check": {
            required: true,
            minlength: 8,
            passmatch: true,
        },
        "tos": {
            required: true,
            minlength: 6,
        }
    },
    messages: {
        email: {
            required: " is Required",
            email: " is Improperly Formatted",
            remote: " already exists",
            },

        },
        password: {
            required: " is Required",
            minlength: " requires at least 8 characters",
        },
        "password-check": {
            required: " is Required",
            minlength: " requires at least 8 characters",
            passmatch: " must match the Passphrase",
        },
        tos: {
            required: " is Required",
            minlength: " requires at least 6 characters",
        },                      
    },
    onkeyup: true,
    onblur: true
});

And, in the ideal, I'd love something like this:

messages: {
email: {
    required: " is Required",
    email: " is Improperly Formatted",
    remote: " already exists",
    remote: {
        username: function() {
        var emailcheck = $('#email').val();  
        return $('#username_availability_result').html(emailcheck + ' is already in our system. Please <a href="/login.php">log in here</a>.');
        },
    },
},              
},

Thanks again, and in advance, for your own ongoing attention and advice,

Z

ORIGINAL QUESTION


I'm using jQuery Validate to run routine validation on a registration form. But one of the features I wanted to add to the form's functionality was an AJAX check to determine if an email address was already in the system. The problem is that the email check function exists outside of the validate function, and so doesn't actually stop the form from submitting when necessary.

Here's my code. (The top 50 lines prise validation and password matching. The remainder constitutes the AJAX check [which is triggered by the email field's keyup event]).

        // Method adds password matching abilities to the validator
        jQuery.validator.addMethod("passmatch", function(value, element) {
           return $('#password').val() == $('#password-check').val()
        }, "* Passwords should match");

        $(document).ready(function(){
            $("#signup").validate({
                errorElement: "span",
                errorPlacement: function(error, element) {
                    error.appendTo(element.prev());
                    //element.prev().replaceWith(error);
                },
                rules: {
                    "email": {
                        required: true,
                        email:true,
                    },
                    "password": {
                        required: true,
                        minlength: 8,
                    },
                    "password-check": {
                        required: true,
                        minlength: 8,
                        passmatch: true,
                    },
                    "tos": {
                        required: true,
                        minlength: 6,
                    }
                },
                messages: {
                    email: {
                        required: " is Required",
                        email: " is Improperly Formatted",
                    },
                    password: {
                        required: " is Required",
                        minlength: " requires at least 8 characters",
                    },
                    "password-check": {
                        required: " is Required",
                        minlength: " requires at least 8 characters",
                        passmatch: " must match the Password"
                    },
                    tos: {
                        required: " is Required",
                        minlength: " requires at least 6 characters",
                    },                      
                }
            });

            //check email availability 
            $('#email').keyup(function(){  
                check_availability();  
            });  

        });               

        //function to check username availability  
        function check_availability(){  

                //get the username  
                var username = $('#email').val();  

                //use ajax to run the check  
                $.post("/ajax/emailcheck.php", { username: username },  
                    function(result){  
                        //if the result greater than none  
                        if(result > 0 ){  
                            //show that the username is not available  
                            $('#username_availability_result').html(username + ' is already in our system. Please <a href="/login.php">log in here</a>.');  
                        }else{  
                            //username available.  
                            //clear any messages
                            $('#username_availability_result').html(''); 
                        }  
                });  
        }  

Is there a way for the check_availability() function to trigger a stop (and a start once it's cleared) so that the form can't be submitted during a state of error? Or can the whole kit and caboodle somehow be integrated into Validate using addMethod (if so, please note that I'm providing availability feedback in a specifically IDed element, not through the same element where other Validate errors appear)?

Thanks in advance for all your help and advice.

Z

UPDATE


Thanks to charlietfl's ments and suggestions (and, at one point ire, lol - apologies for my faux pas), I've finally got the system checking from within Validate, and the form submission is halted when the email is sent. So I guess my question is answered, but if you'll all bear with me for one more moment, there's one last finishing touch that I could use your help with...

In my original vision, in addition to triggering a proper "Email already exists" error, I also populated a second element with some HTML that more pletely explained the situation to the user and provided a link to a login form. This second element appeared and disappeared depending on the status of the field.

Is there a way to use the messages/remote section to do this as well?

Here what I have:

$(document).ready(function(){
$("#signup").validate({
    errorElement: "span",
    errorPlacement: function(error, element) {
        error.appendTo(element.prev());
        //element.prev().replaceWith(error);
    },
    rules: {
        "email": {
            required: true,
            email:true,
            remote: {
                url: "/ajax/emailcheck.php",
                type: "post",
            },
        },
        "password": {
            required: true,
            minlength: 8,
        },
        "password-check": {
            required: true,
            minlength: 8,
            passmatch: true,
        },
        "tos": {
            required: true,
            minlength: 6,
        }
    },
    messages: {
        email: {
            required: " is Required",
            email: " is Improperly Formatted",
            remote: " already exists",
            },

        },
        password: {
            required: " is Required",
            minlength: " requires at least 8 characters",
        },
        "password-check": {
            required: " is Required",
            minlength: " requires at least 8 characters",
            passmatch: " must match the Passphrase",
        },
        tos: {
            required: " is Required",
            minlength: " requires at least 6 characters",
        },                      
    },
    onkeyup: true,
    onblur: true
});

And, in the ideal, I'd love something like this:

messages: {
email: {
    required: " is Required",
    email: " is Improperly Formatted",
    remote: " already exists",
    remote: {
        username: function() {
        var emailcheck = $('#email').val();  
        return $('#username_availability_result').html(emailcheck + ' is already in our system. Please <a href="/login.php">log in here</a>.');
        },
    },
},              
},

Thanks again, and in advance, for your own ongoing attention and advice,

Z

ORIGINAL QUESTION


I'm using jQuery Validate to run routine validation on a registration form. But one of the features I wanted to add to the form's functionality was an AJAX check to determine if an email address was already in the system. The problem is that the email check function exists outside of the validate function, and so doesn't actually stop the form from submitting when necessary.

Here's my code. (The top 50 lines prise validation and password matching. The remainder constitutes the AJAX check [which is triggered by the email field's keyup event]).

        // Method adds password matching abilities to the validator
        jQuery.validator.addMethod("passmatch", function(value, element) {
           return $('#password').val() == $('#password-check').val()
        }, "* Passwords should match");

        $(document).ready(function(){
            $("#signup").validate({
                errorElement: "span",
                errorPlacement: function(error, element) {
                    error.appendTo(element.prev());
                    //element.prev().replaceWith(error);
                },
                rules: {
                    "email": {
                        required: true,
                        email:true,
                    },
                    "password": {
                        required: true,
                        minlength: 8,
                    },
                    "password-check": {
                        required: true,
                        minlength: 8,
                        passmatch: true,
                    },
                    "tos": {
                        required: true,
                        minlength: 6,
                    }
                },
                messages: {
                    email: {
                        required: " is Required",
                        email: " is Improperly Formatted",
                    },
                    password: {
                        required: " is Required",
                        minlength: " requires at least 8 characters",
                    },
                    "password-check": {
                        required: " is Required",
                        minlength: " requires at least 8 characters",
                        passmatch: " must match the Password"
                    },
                    tos: {
                        required: " is Required",
                        minlength: " requires at least 6 characters",
                    },                      
                }
            });

            //check email availability 
            $('#email').keyup(function(){  
                check_availability();  
            });  

        });               

        //function to check username availability  
        function check_availability(){  

                //get the username  
                var username = $('#email').val();  

                //use ajax to run the check  
                $.post("/ajax/emailcheck.php", { username: username },  
                    function(result){  
                        //if the result greater than none  
                        if(result > 0 ){  
                            //show that the username is not available  
                            $('#username_availability_result').html(username + ' is already in our system. Please <a href="/login.php">log in here</a>.');  
                        }else{  
                            //username available.  
                            //clear any messages
                            $('#username_availability_result').html(''); 
                        }  
                });  
        }  

Is there a way for the check_availability() function to trigger a stop (and a start once it's cleared) so that the form can't be submitted during a state of error? Or can the whole kit and caboodle somehow be integrated into Validate using addMethod (if so, please note that I'm providing availability feedback in a specifically IDed element, not through the same element where other Validate errors appear)?

Thanks in advance for all your help and advice.

Z

Share Improve this question edited Jun 25, 2012 at 13:21 Shikarnov asked Jun 24, 2012 at 22:59 ShikarnovShikarnov 811 gold badge1 silver badge10 bronze badges 3
  • Not really an answer, so I guess a ment, but you could try using my own plugin that does pretty much what jQuery validate does plus much more... github./elclanrs/jq-idealforms. You can acplish what you want with the exclude filter passing in an array of values to exclude. – elclanrs Commented Jun 24, 2012 at 23:07
  • Thank you for your ment. I looked at your plugin and it seems pretty neat. I didn't see where it would allow me to query against my database to check if a username was available. Did I miss something? – Shikarnov Commented Jun 24, 2012 at 23:22
  • Oh well, in reality you'll have to make your own query helper function to grab data from the database but if you save that data in an array and pass it in with the exclude filter then it'll get close to what you're after. – elclanrs Commented Jun 24, 2012 at 23:24
Add a ment  | 

2 Answers 2

Reset to default 3

Use the remote option of validation plugin that already has a built in ajax method that will bind to the input

http://docs.jquery./Plugins/Validation/Methods/remote#options

Alternatively required can also be a function ( will not work on keyup or blur)

email:{ required: function(){
          return $('#username_availability_result').html()=='';
   }

}

Also, why not reset the email field if ajax returns a duplication? Your code would likely work as is with a reset of the field

Best suggestion is use built in remote

    <script language="javascript" type="text/javascript">
        $(document).ready(function() {
            $("#singupfrom").validate({
                rules: {

                    'useremail': {// pound rule
                        required: true,
                        email: true,



                        remote:{


                            url: "check_email.php",
                            type: "post",

                            data:
                            {
                                emails: function()
                                {
                                    return $('#singupfrom :input[name="useremail"]').val();
                                }
                            }


                        }
                    }

                },
                  // here custom message for email already exists
                 messages: {
                    useremail: { remote: "Email already exists"}

                }

            });

        });
    </script>

    <!-- your user email-->

                                <label>Email :</label>
                                <input type="text" name="useremail" id="useremail" value=""  />
    <!-- your user email end -->



    // your  php file "check_email.php"  will be some thing like it 
    /// get or post can also be used in place of request depending on situation
    $email = $_REQUEST['useremail'];


    <?php 
            $check   = "your query to check the email and returns the no of rows/ emails exists ";
            if ($check == '0' or empty($check)) {
                echo 'true';
            } else {
                echo  'false';

            }

?>
发布评论

评论列表(0)

  1. 暂无评论