12

我想弄清楚我怎么能把它变成这样:

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

接近这个:

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

            }
        }

但是我很难完成它。我想要的是让它显示错误消息而不是警报,但我可以在实际的 jquery 验证消息中设置消息。

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

更新:

出于某种原因,它没有将其作为 POST 执行,而是将其作为 GET 请求执行,但不知道为什么。这是更新的代码:

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!'
                        }
                    }
                }

            }
        },

更新 2:

现在我已经到了某个地方,我又回到了获取 POST 请求的地方。我还有两个问题。其中之一是要完成另一个 POST 请求,用户必须刷新表单。最后一个问题是,如果找到返回的用户名,它不会显示错误消息。

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!'
                        }
                    }
                }

            }
        },

更新:

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

更新 4:

控制器:

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;
    }        
}

模型:

/**
 * 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;
    }
}
4

8 回答 8

25

完成此操作的最简单方法是简单地将true错误消息作为字符串返回,或者false从您的服务器端资源返回。根据远程的jQuery验证文档

响应被评估为 JSON 并且对于有效元素必须为 true,并且对于无效元素可以是任何 false、未定义或 null,使用默认消息;或字符串,例如。“该名称已被占用,请尝试 peter123”以显示为错误消息。

这意味着如果您可以更改服务器端代码以true在验证成功时返回或在验证不成功时更改错误消息(“用户名已在使用”),您只需编写以下远程规则:

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

您也可以简单地从服务器端资源返回true或返回并在客户端上定义错误消息。false在这种情况下,您将拥有上述规则,然后是messages对象中的一个属性:

messages: {
    username: {
        remote: "username already in use"
    }
}
于 2012-06-05T21:21:18.003 回答
10

我知道为时已晚,但这可以帮助其他人。

远程方法旨在接收 Json 字符串,因此您的服务器端应该向该方法返回类似的内容...

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

这是我在尝试验证用户昵称时编写的 JS 代码示例。

$(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"
                }
            }
        });});

希望它可以帮助某人,它帮助了我。

于 2014-09-09T17:00:59.033 回答
7

我意识到这已经过时了,但我很难让它也能正常工作,并想分享对我有用的东西。

客户端表单验证代码:

$('#frmAddNew').validate({
onkeyup: false,
rules: {
    ADID: {
        required: true,
        alphanumeric: true,
        maxlength: 10,
        remote: {
            url: "ADIDValidation.cshtml",
            type: "post",
            dataType: "json",
            dataFilter: function (data) {
                if (data) {
                    var json = $.parseJSON(data);
                    if (json[0]) {
                        return JSON.stringify(json[0].valid) /* will be "true" or whatever the error message is */
                    }
                }
            },
            complete: function (data) {
               /* Additional code to run if the element passes validation */
                if (data) {
                    var json = $.parseJSON(data.responseText);
                    if (json[0]) {
                        if (json[0].valid === "true") {
                            $('#FirstName').val(json[0].FirstName);
                            $('#LastName').val(json[0].LastName);
                        }
                    }
                }
            }
        }
    }
},
messages: {
    ADID: {
        required: "Please Enter an ADID of the Employee",
        alphanumeric: "The ADID Can Only Contain Letters and Numbers",
        maxlength: "ADID For User's Current Permissions Must Be 10 Characters or Less"
    }
},
submitHandler: function (form) {
    form.submit();
},
errorContainer: $('section.errorCon'),
errorLabelContainer: $('ol', 'section.errorCon'),
wrapper: 'li',
showErrors: function (errors) {
    var error = this.numberOfInvalids();
    var message = error == 1
        ? 'You missed 1 field:'
        : 'You missed ' + error + ' fields:';
    $('section.errorCon h3').html(message);
    this.defaultShowErrors();
}
});

ADIDValidation.cshtml 的服务器端代码(我正在使用 Razor 网页):

@{

Layout = null;

if(IsPost)
{
    var db = Database.Open("<enter connection name>");
    var sql = "<enter sql or stored procedure>";
    var strADID = Request["ADID"];

    var result = db.Query(sql, strADID);
    IEnumerable<dynamic> response;

    if(result.Any()) 
    {
        @* "true" indicates the element passes validation. Additional data can be passed to a callback function *@
        response = result.Select(x => new
        {
            valid = "true",
            FirstName = x.FirstName,
            LastName = x.LastName
        });
    }

    else
    {
        @* The element did not pass validation, the message below will be used as the error message *@
        response = new[] {
            new {valid = "The Employee's ADID '" + strADID.ToString() + "' Is Not Valid. Please Correct and Resubmit"}
        };
    }

    Json.Write(response, Response.Output);
}
}
于 2016-03-18T19:40:15.833 回答
0

我最近需要在 Rails 项目中进行远程验证,如果输入无效,我很难从服务器端发送正确的响应。最后,解决方案非常简单。

如果服务器端检查返回 true,您可以发送 true 或“true”,否则您可以返回任何字符串,例如“电子邮件已存在”或“电子邮件没有有效的 MX 记录”。此字符串将显示为表单上的验证消息。唯一的问题是从服务器端返回的消息字符串应该是有效的 JSON,并且应该是这种格式 - [“电子邮件已经存在”]。

关于我如何调试并找到解决方案的一些解释:请参阅下面的 jquery.validate.js 中的远程方法。我在 ajax 调用中添加了日志语句和错误函数以进行调试。当我从服务器端返回一个普通字符串时,抛出了一个 jQuery.parseJson 错误。

// http://jqueryvalidation.org/remote-method/

remote: function( value, element, param ) {
    if ( this.optional( element ) ) {
        return "dependency-mismatch";
    }

    var previous = this.previousValue( element ),
        validator, data;

    if (!this.settings.messages[ element.name ] ) {
        this.settings.messages[ element.name ] = {};
    }
    previous.originalMessage = this.settings.messages[ element.name ].remote;
    this.settings.messages[ element.name ].remote = previous.message;

    param = typeof param === "string" && { url: param } || param;

    if ( previous.old === value ) {
        return previous.valid;
    }

    previous.old = value;
    validator = this;
    this.startRequest( element );
    data = {};
    data[ element.name ] = value;

    $.ajax( $.extend( true, {
        url: param,
        mode: "abort",
        port: "validate" + element.name,
        dataType: "json",
        data: data,
        context: validator.currentForm,
        success: function( response ) {
            console.log("response is "+response);
            var valid = response === true || response === "true",
                errors, message, submitted;
            console.log("valid is "+valid);
            validator.settings.messages[ element.name ].remote = previous.originalMessage;
            if ( valid ) {
                submitted = validator.formSubmitted;
                validator.prepareElement( element );
                validator.formSubmitted = submitted;
                validator.successList.push( element );
                delete validator.invalid[ element.name ];
                validator.showErrors();
            } else {
                errors = {};
                message = response || validator.defaultMessage( element, "remote" );
                console.log("else message is "+message);
                errors[ element.name ] = previous.message = $.isFunction( message ) ? message( value ) : message;
                validator.invalid[ element.name ] = true;
                console.log("else errors[ element.name ] "+errors[ element.name ]);
                validator.showErrors( errors );
            }
            previous.valid = valid;
            validator.stopRequest( element, valid );
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.status);
            console.log(thrownError);
        }
    }, param ) );
    return "pending";
}
于 2015-08-15T13:27:43.377 回答
0
rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: 'register/isUsernameAvailable',
         }
        }

您需要传递用户名

于 2016-02-23T14:12:05.730 回答
0

我想我来不及回复了。但是我们的代码对所有人来说都很容易

验证码

rules: {
            session: {
               required: true,
                remote: {
                    url: "<?php echo base_url('setting/session_setting/checkSession'); ?>",
                    type: "post",
                    data: {
                      session: function() {
                        return $( "#sessionInput" ).val();
                      }
                    }
                  }
            },
        },

控制器代码

public function checkSession()
    {
        $response = array();
        $session = $this->input->post('session');

        $check = $this->dm->checkData('session','session',array('session'=>$session));

        if($check)
        {
            echo(json_encode("Session Already Exist")); 
        }
        else
        {
            echo(json_encode(true)); 
        }
    }

型号代码

public function checkData($data,$tablename,$where)
    {
        $query = $this->db->select($data)
                 ->from($tablename)
                 ->where($where)
                 ->get();
        if($query->num_rows() > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
于 2019-06-21T16:53:04.617 回答
0
Jquery Code: 
 rules: {
        email: {
                required: true,
                maxlength: 50,
                email: true,
                 remote: {
        url: "<?php echo base_url('user/email_check') ?>",
        type: "post",
        data: {
          email: function() {
            return $( "#email" ).val();
          }
        }
      }
            },     
    },
     messages: {
      email: {
          required: "E-mailadres",
          email: "Please enter valid email",
          maxlength: "The email name should less than or equal to 50 characters",
          remote: jQuery.validator.format("{0} is already taken.")
        },
    },

PHP Code:
  if($results->num_rows == 0)
    {
        echo "true";  //good to register
    }
    else
    {
        echo "false"; //already registered
    }
于 2020-05-29T08:24:31.837 回答
-2

好吧,我不知道你的插件概念,但我想你希望它检查用户名是否大于 6 或小于 12。从没有插件的 jQuery 核心示例中,它就像添加一样简单一点点 if-else 的概念。

$('#username').blur(function(){
    if($('#username').val().length < 6 || $('#username').val().length > 12)
    {
        alert('Username must be between 6 and 12 characters');
    }
    else
    {
       $.post('register/isUsernameAvailable', 
              {"username":$('#username').val()}, 
              function(data){
                  if(data.username == "found"){
                      alert('username already in use');
                  }
              }, 'json');
    }
});
于 2012-06-05T19:05:10.980 回答