jQuery Validator Plugin - check for existing Username/Email in mysql database

46,886

Solution 1

$.validator.addMethod("checkExists", function(value, element)
{
    var inputElem = $('#register-form :input[name="email"]'),
        data = { "emails" : inputElem.val() },
        eReport = ''; //error report

    $.ajax(
    {
        type: "POST",
        url: validateEmail.php,
        dataType: "json",
        data: data, 
        success: function(returnData)
        {
            if (returnData!== 'true')
            {
              return '<p>This email address is already registered.</p>';
            }
            else
            {
               return true;
            }
        },
        error: function(xhr, textStatus, errorThrown)
        {
            alert('ajax loading error... ... '+url + query);
            return false;
        }
    });

}, '');

OR

You can use the remote method instead which allows you to do remote checks: http://docs.jquery.com/Plugins/Validation/Methods/remote

Eg.

    $("#yourFormId").validate({
            rules: {
                email: {
                    required: true,
                    email: true,
                    remote: {
                        url: "checkUnameEmail.php",
                        type: "post"
                     }
                }
            },
            messages: {
                email: {
                    required: "Please Enter Email!",
                    email: "This is not a valid email!",
                    remote: "Email already in use!"
                }
            }
        });

checkUnameEmail.php //Eg.

    <?php
    $registeredEmail = array('[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]');

    $requestedEmail  = $_REQUEST['email'];

    if( in_array($requestedEmail, $registeredEmail) ){
        echo 'false';
    }
    else{
        echo 'true';
    }
    ?>

Solution 2

js code

username: {
        required: true,
        minlength: 5,
        remote: '/userExists'
       },

Php code to check if exist and return messages

public function userExists()
{
    $user = User::all()->lists('username');
    if (in_array(Input::get('username'), $user)) {
        return Response::json(Input::get('username').' is already taken');
    } else {
        return Response::json(Input::get('username').' Username is available');
    }
}
Share:
46,886
user2910809
Author by

user2910809

Updated on October 17, 2020

Comments

  • user2910809
    user2910809 over 3 years

    I've successfully created a form that submits and adds users to a mysql database, and form validation with 'jQuery Validator' plugin works great for everything except checking to see if the username already exists in the database...

    I've just spent about 8 hours reading and trying to figure out a way to define a new method with the 'jQuery Validator' plugin. I just can't seem to understand how I would go about checking the database for the entered username or email and return whether it already exists or not using jQuery.

    My code:

    <script src="../assets/js/main.js"></script>
    <script src="../assets/js/ajax.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
    <!-- FORM VALIDATION -->
    <script type="text/javascript">
    
    
        jQuery.validator.addMethod("checkExists", 
    function(value, element) {
        //No idea what to call here
    }, 
    "Username already exists."
    );
    
    
            //<![CDATA[
            $(window).load(function(){
            $("form").validate({
            rules: {
                username: {minlength: 3, required: true, checkExists: true},
                email: {email: true, required: true},
                pass1: {minlength: 3, required: true},
                pass2: {minlength: 3, required: true, equalTo: "#pass1"},
                country: {required: true},
                tandc: {required: true},
            },
            messages: {
            username:   {required: "You need to enter a Username."},
            email:      {required: "You need to enter an Email Address."},
            pass1:      {required: "You need to enter a Password."},
            pass2:      {required: "You need to enter your password again.", equalTo: "Your passwords don't match."},
            country:    {required: "You need to tell us where you live."},
            tandc:      {required: "You need to read and agree to the Terms and Conditions to use CGE."}
            },
    
    
            showErrors: function(errorMap, errorList) {
            $.each(this.successList, function(index, value) {
            return $(value).popover("hide");
            });
            return $.each(errorList, function(index, value) {
            var _popover;
            console.log(value.message);
            _popover = $(value.element).popover({
            trigger: "manual",
            placement: "right",
            content: value.message,
            template: "<div class=\"popover\"><div class=\"arrow\"></div><div class=\"popover-inner\"><div class=\"popover-content\"><p></p></div></div></div>"
            });
            _popover.data("popover").options.content = value.message;
            return $(value.element).popover("show");
            });
            }
            });
            });//]]>
    </script>
    

    If anyone clever could please amend my code to show me how I should have done it, it would be a great help - I feel like I'm about to go crazy!

    Thanks in advance, can't wait to see the solution :-)


    EDIT - This is my current code

    Nothing seems to happen at all, I feel like I'm closer though:

    CURRENT CODE:

    signup.php

        $(window).load(function(){
                $("form").validate({
                rules: {
                    username: {minlength: 3, required: true},
                    email: {email: true, required: true, remote: {url: "./validation/checkUnameEmail.php", type : "post"}},
                    pass1: {minlength: 3, required: true},
                    pass2: {minlength: 3, required: true, equalTo: "#pass1"},
                    country: {required: true},
                    tandc: {required: true}
    },
    

    checkUnameEmail.php

    <?php
        include_once(".../php_includes/db_conx.php");
        $email = urldecode($_POST['email']);
        $result = mysqli_query($db_conx, "SELECT * FROM users WHERE email = '$email' LIMIT 1;");
        $num = mysqli_num_rows($result);
        if($num == 0){
            echo "true";
        } else {
            echo "E-Mail-Adresse schon registriert.";
        }
        mysqli_close($db_conx);
    ?>
    

    *db_conx.php*

    <?php
    $db_conx = mysqli_connect("localhost", "root", "root", "membership");
    //Evlauate the connection
    if (mysqli_connect_errno()){
        echo mysqli_connect_error();
        exit();
    }
    ?>
    
  • user2910809
    user2910809 over 10 years
    This looks great, thanks for such a quick reply! I don't understand why the additional "return $("#email").val();" is there? Would that not be sending the email address twice? Also what should checkUnameEmail.php contain? Thanks again, you have no idea how much I appreciate this
  • Jenson M John
    Jenson M John over 10 years
    checkUnameEmail.php where you actually need to check the existence of username/email.
  • user2910809
    user2910809 over 10 years
    I updated my question with my current code, I think you've gotten me a lot closer - there's probably just one little thing that's causing it not to work.
  • Jenson M John
    Jenson M John over 10 years
    You can do echo "false" in checkUnameEmail.php else part & in validator message section add remote: "E-Mail-Adresse schon registriert." for email.
  • user2910809
    user2910809 over 10 years
    I've made the suggested changes Jenson and I'm getting a response, but its always true. But if I actually navigate to "/validation/[email protected]", it works perfectly and echos out true if the email is available and false if it is already in the database.
  • Jenson M John
    Jenson M John over 10 years
    @user2910809 Have you set message for email remote rule?
  • Jenson M John
    Jenson M John over 10 years
    Please Check Updated Code.
  • user2910809
    user2910809 over 10 years
    Thanks Jenson, I just saw your reply. Changing remote's type from 'post' to 'get' fixed it. It now notifies of duplicate username and email perfectly :-) only thing is that the form can still be submitted regardless of this, I'll have to try figure that out. You saved a n00b's life today, thanks Jenson.