rohit
rohit

Reputation: 145

Adding custom rule to jquery validation for checking unique username

I am trying to add a custom rule to check uniqueness of username in my jquery validation function, but it doesn't return any result. When I alert the msg variable it alerts correctly.

Here's my code:

jQuery(document).ready(function() {
    var validator = $("#frmregister").validate({
        rules: {
            "txtName":"required",
            txtuName: {
                required:true,
                usernameCheck:true    // remote check for duplicate username
            },
        },
        messages: {
            txtuName:{
                required:"Please enter User name",
                usernameCheck:"this username is already in use."
            },
        },
        highlight: function( element, errorClass, validClass ) {
            $(element).removeClass(validClass);
        },
        errorElement: 'div'
    });
});

jQuery.validator.addMethod('usernameCheck', function(txtuName) {
    var burl=$("#bseurl").val();

    //alert(burl);
    var postURL = burl+"home/usernamechk";
    //alert(postURL);
    var cnt = $("#frmregister").serialize();

   jQuery.ajax({
      type: "POST",
      data: cnt,
      url: postURL,
      success: function(msg) {
          result = (msg== 2) ? true : false;
      }
      return result;
   });
}, '');

Upvotes: 0

Views: 1271

Answers (1)

Barmar
Barmar

Reputation: 782508

That doesn't look like valid Javascript syntax. return result is inside an object. But the real problem is that AJAX is asynchronous, so the validator method returns without waiting for results from AJAX.

jquery-validate provides a remote: validation method that takes care of waiting for the response. The server just has to return true or false as JSON.

Upvotes: 1

Related Questions