Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the remote function of jquery validation

I'm trying to figure out how I can turn this:

$('#username').blur(function(){
    $.post('register/isUsernameAvailable', 
           {"username":$('#username').val()}, 
           function(data){
               if(data.username == "found"){
                   alert('username already in use');
               }
           }, 'json');
});

into something close to this:

rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: {
                url: 'register/isUsernameAvailable',
                type: 'post',
                data: {
                    'username': $('#username').val()
                } 

            }
        }

However I'm having a hard time finishing it off. What I want is instead of the alert to have it display the error message but I can set the message inside the actual jquery validation messages.

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

UPDATE:

For some reason its not doing it as a POST its doing it as a GET request and not sure why. Here's the updated code:

rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: {
                url: 'register/isUsernameAvailable',
                dataType: 'post',
                data: {
                    'username': $('#username').val()
                },
                success: function(data) {
                    if (data.username == 'found')
                    {
                        message: {
                            username: 'The username is already in use!'
                        }
                    }
                }

            }
        },

UPDATE 2:

Now I'm getting somewhere I'm back to getting the POST request. I'm getting two more problems. One of which is the fact that for another POST request to be done the user has to refresh the form. And the last problem is that if the returned username is found it DOES NOT show the error message.

rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: {
                type: 'post',
                url: 'register/isUsernameAvailable',
                data: {
                    'username': $('#username').val()
                },
                dataType: 'json',
                success: function(data) {
                    if (data.username == 'found')
                    {
                        message: {
                            username: 'The username is already in use!'
                        }
                    }
                }

            }
        },

UPDATE:

public function isUsernameAvailable()
{
    if ($this->usersmodel->isUsernameAvailable($this->input->post('username')))
    {
        return false;
    }
    else
    {
        return true;
    }        
}

UPDATE 4:

Controller:

public function isUsernameAvailable()
{
    if ($this->usersmodel->isUsernameAvailable($this->input->post('username')))
    {
        return false;
    }
    else
    {
        return true;
    }        
}

public function isEmailAvailable()
{
    if ($this->usersmodel->isEmailAvailable($this->input->post('emailAddress')))
    {
        return false;
    }
    else
    {
        return true;
    }        
}

MODEL:

/**
 * Check if username available for registering
 *
 * @param   string
 * @return  bool
 */
function isUsernameAvailable($username)
{
    $this->db->select('username');
    $this->db->where('LOWER(username)=', strtolower($username));
    $query = $this->db->get($this->usersTable);
    if ($query->num_rows() == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * Check if email available for registering
 *
 * @param   string
 * @return  bool
 */
function isEmailAvailable($email)
{
    $this->db->select('email');
    $this->db->where('LOWER(email)=', strtolower($email));
    $query = $this->db->get($this->usersTable);
    if($query->num_rows() == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
like image 388
Jeff Davidson Avatar asked Jun 05 '12 18:06

Jeff Davidson


People also ask

What is remote validation in jQuery?

According to the jQuery validate documentation for remote: The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.

How do you check if jQuery validate is working?

fn , so simply check whether it exists or not; if (typeof jQuery. fn. validationPlugin === "function") { // It's loaded } else { // It's not. }

How we can use jQuery validation plugins in MVC?

UnobtrusiveJavaScriptEnabled" property value back to false and create a new file in "Scripts" folder and name it "script-custom-validator. js". Add the Jquery validator code in it as shown below i.e. The above piece of code attaches my account register form with jQuery form validator by using form ID.


2 Answers

The easiest way to accomplish this is to simply return true, an error message as a string, or false from your server-side resource. According to the jQuery validate documentation for remote:

The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.

This means if you can change your server-side code to return true in the event of successful validation or an error message ("username already in use") in the event of unsuccessful validation, you could just write the following remote rule:

remote: {
    type: 'post',
    url: 'register/isUsernameAvailable',
    data: {
        'username': function () { return $('#username').val(); }
    },
    dataType: 'json'
}

You could also simply return true or false from your server-side resource and define the error message on the client. In that case you would have the above rule and then a property in the messages object:

messages: {
    username: {
        remote: "username already in use"
    }
}
like image 192
Andrew Whitaker Avatar answered Oct 22 '22 22:10

Andrew Whitaker


I know it's too late, but this could help other people.

The remote method is meant to recieve a Json string, so your server side should be returning something like this to the method...

echo(json_encode(true)); // if there's nothing matching
echo(json_encode(false));

This is an example of the JS code that I wrote while trying to validate user's nickname.

$(document).ready(function(){
            $('#form').validate({
            rules: {
                user_nickname: {
                    remote: {
                        url: "available.php",
                        type: "post",
                        data: {
                          user_nickname: function() {
                            return $( "#user_nickname" ).val();
                          }
                        }
                      }               
                }
            },
            messages:{
                user_nickname: {
                    remote: "Username already taken"
                }
            }
        });});

Hope it helps someone, it helped me.

like image 35
qiqe.f Avatar answered Oct 22 '22 22:10

qiqe.f