2014-10-03 103 views
0

我有这个代码进行验证,但它显示错误,即使它返回true。我将所有返回false更改为true,但显示错误。 秒我想要显示result.message而不是“用户名已被占用”。jquery验证没有工作

$.validator.addMethod("uniqueUserName", function (value, element) { 
     $.ajax({ 
      type: "post", 
      url: "/validation/search", 
      data: { 
       nationalCode: $('#karkonan_MelliCode').val(), 
       personType: $('#karkonan_MelliatCode').val() 
      }, 
      dataType: "json", 
      async: false, 
      success: function (result) { 
       // alert(result.message); 
       // alert(result.resultCode); 
       // if the user exists, it returns a string "true" 
       if (result.resultCode == "0") { 
        alert($('#karkonan_MelliatCode').val());// already exists 
        //j = result.message;// already exists 
        return false; 
       } 
       else { 
        alert($('#karkonan_MelliatCode').val()); 
        return true;  // username is free to use 
       } 
      }, 
      error: function (result) { 
       // if the user exists, it returns a string "true" 
       alert("error"); 
       return false; 
       // username is free to use 
      } 
     }) 
    }, "Username is Already Taken"); 

,它的规则是:

'karkonan.MelliCode': { 
         number:true, 
         minlength: 10, 
         maxlength: 10, 
         required: true, 
         withmelliat:true, 
         uniqueUserName: true 
        }, 

回答

1

addMethod可能马上要回调的响应。

您执行一个Ajax并且响应是异步的。您的successerror处理程序中的return语句不适用addMethod返回值(在Ajax请求之后和响应之前立即完成)。

要检查,添加这里return true;

}); 
    return true; 
}, "Username is Already Taken"); 

我没有带解决方案还没有,我(和你)来读取你的validator plugin documentation

您还必须阅读该插件的remote属性:here the documentation

+0

动态result.message怎么样?我可以显示动态消息吗? – 2014-10-03 07:44:20

+0

没关系。我发现我如何使用动态消息。谢谢。 – 2014-10-03 07:55:48

0

error被称为如果AJAX请求失败,如果您的脚本返回一些错误不会! 这个函数接收三个参数:

jqXHR(jQuery中1.4.x中,XMLHttpRequest)对象,描述错误的发生的类型和一个可选的异常对象,如果发生一个字符串。

作为第二个参数(除了null)可能的值是timeouterrorabort,并parsererror。发生HTTP错误时,errorThrown会收到HTTP状态的文本部分,例如Not FoundInternal Server Error

从jQuery 1.5开始,错误设置可以接受一组函数。每个函数都会依次调用。 注意:此处理程序是未调用跨域脚本和跨域JSONP请求。

有争议的是,如果AJAX请求本身成功,即如果浏览器可以正确发送请求,success是一个函数,称为

这个函数会得到三个参数:

的数据从服务器返回,根据dataType参数格式化;描述状态的字符串;和jqXHR(在jQuery 1.4.x,XMLHttpRequest)对象中。