jQuery验证器和使用AJAX的自定义规则

tha*_*ook 50 validation ajax jquery jquery-validate

我阅读了关于jQuery验证器的回复,其中概述了一种根据数据库中的值检查用户名的方法.

我已经尝试过实现这个方法,但无论从PHP文件返回什么,我总是得到用户名已被取消的消息.

这是自定义方法......

$.validator.addMethod("uniqueUserName", function(value, element) {
  $.ajax({
      type: "POST",
       url: "php/get_save_status.php",
      data: "checkUsername="+value,
      dataType:"html",
   success: function(msg)
   {
      // if the user exists, it returns a string "true"
      if(msg == "true")
         return false;  // already exists
      return true;      // username is free to use
   }
 })}, "Username is Already Taken");
Run Code Online (Sandbox Code Playgroud)

这是验证码...

username: {
    required: true,
    uniqueUserName: true
},
Run Code Online (Sandbox Code Playgroud)

是否有一种特定的方式我应该从PHP返回消息.

谢谢

一个

Tim*_*Tim 62

对于偶然发现这种情况的其他人来说,验证支持"远程"方法,这种方法在2010年可能不存在:

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

$("#myform").validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: {
        url: "check-email.php",
        type: "post",
        data: {
          username: function() {
            return $("#username").val();
          }
        }
      }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)


Jan*_*oom 61

你正在做一个AJAX请求,ergo:当你的自定义验证器返回true或false时,验证已经完成.

你需要合作async.另请参阅此文章:如何让jQuery执行同步而非异步的Ajax请求?

就像是:

function myValidator() {
   var isSuccess = false;

   $.ajax({ url: "", 
            data: {}, 
            async: false, 
            success: 
                function(msg) { isSuccess = msg === "true" ? true : false }
          });
    return isSuccess;
}
Run Code Online (Sandbox Code Playgroud)

警告:

从jQuery 1.8开始,不推荐使用async:false和jqXHR($ .Deferred); 您必须使用success/error/complete回调选项而不是jqXHR对象的相应方法,例如jqXHR.done()或不推荐使用的jqXHR.success().

  • 对于将来磕磕绊绊的人,async已被弃用.请参阅Tim的答案. (12认同)
  • 如果服务器验证需要时间,它将冻结页面。 (2认同)

JnJ*_*Boo 11

我花了很长时间才弄清楚如何将包含页面中元素值的jsonified字符串放入远程请求中 - 这是多小时组合并尝试多次搜索结果的结果.

关键点:

  1. async:false 已被弃用,
  2. 函数调用后remote:是用于创建具有元素值的数据字符串的键.尝试从表单中访问当前值后data:返回dataType设置为json 的字段的空白值.

        $("#EmailAddress").rules("add", {
        required: true,
        remote: function () { // the function allows the creation of the data string 
                              // outside of the remote call itself, which would not 
                              // return a current value from the form.
            var emailData = "{'address':'" + 
                            $('#SignupForm :input[id$="EmailAddress"]').val() + 
                            "'}";
            var r = {
                url: "foobar.aspx/IsEmailAvailable",
                type: "post",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                cache: false,
                data: emailData,
                dataFilter: function(response) {
                    this.email_run = true; //fix for race condition with next button
                    return isAvailable(data); //return true or false
                }
            };
            return r;
        },
        messages: {
            remote: "* Email in use"
        }
    });
    
    Run Code Online (Sandbox Code Playgroud)

.ASPX页面:

<input id="EmailAddress" required name="Email" type="email" placeholder="Email Address*" runat="server"/>
Run Code Online (Sandbox Code Playgroud)

C#代码背后:

[WebMethod]
    public static object IsEmailAvailable(string address){...}
Run Code Online (Sandbox Code Playgroud)

格式化响应对象:

function isAvailable(data) {
    var response = JSON.parse(getJsonObject(data));
    return (response.isAvailable === "True") ? true : false;
};

//transform response string to a JavaScript Object()
//http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/ 
function getJsonObject(data) {
    var msg = eval('(' + data + ')');
    if (msg.hasOwnProperty('d'))
        return msg.d;
    else
        return msg;
};
Run Code Online (Sandbox Code Playgroud)