代码之家  ›  专栏  ›  技术社区  ›  Aaron Hathaway

jQuery验证插件

  •  2
  • Aaron Hathaway  · 技术社区  · 16 年前

    我真的想避免问这个问题。我已经看到了很多关于这个插件的帖子,但是他们还是不太了解我。现在我有一个新的帐户注册表,我正在尝试编写一个自定义方法来验证一个唯一的用户名。我认为以下措施应该奏效:

    $.validator.addMethod(
            "uniqueUsername", 
            function(value, element) {
                $.post(
                    "http://" + location.host + "/scripts/ajax/check_username.php",
                    {
                        username: value
                    },
                    function(response) {
                        if(response == 'true') {
                            return true;
                        } else {
                            return false;
                        }
                    }
                );
            },
            "This username is already taken."
        );
    

    var result = false;
        $.validator.addMethod(
            "uniqueUsername", 
            function(value, element) {
                $.post(
                    "http://" + location.host + "/scripts/ajax/check_username.php",
                    {
                        username: value
                    },
                    function(response) {
                        if(response == 'true') {
                            result = true;
                        } else {
                            result = false;
                        }
                    }
                );
                return result;
            },
            "This username is already taken."
        );
    

    但是它似乎有一个延迟,因为它存储了值,然后在下一个事件上设置值。你们推荐什么?

    2 回复  |  直到 12 年前
        1
  •  2
  •   Nick Craver    16 年前

    因为这是一个异步检查,所以需要更多的检查(不能从这样的函数返回值,在您的情况下它总是false)。内置方法是 remote

    $("form").validate({
      rules: {
        username: {
          remote: {
            url: "http://" + location.host + "/scripts/ajax/check_username.php",
            type: "post"
          }
        }
      }  
    });
    

    这将发布一个 username: valueofElement 因为规则是针对名为 username . 服务器端脚本应该返回 true 如果验证通过, false 否则…所以 如果用户名已被占用。

    You can read more about the remote option here ,包括如何在需要时传递其他数据参数。

        2
  •  -1
  •   Canaan Etai    12 年前

    username: {
            required: true,
            minlength: 5,
            remote: '/userExists'
           },
    

    Php代码检查是否存在并返回消息

    public function userExists()
    {
        $user = User::all()->lists('username');
        if (in_array(Input::get('username'), $user)) {
            return Response::json(Input::get('username').' is already taken');
        } else {
            return Response::json(Input::get('username').' Username is available');
        }
    }
    
    推荐文章