jQuery验证检查用户名与远程 [英] Jquery Validation check username with remote

查看:138
本文介绍了jQuery验证检查用户名与远程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的验证插件和Laravel 4.2。 我试图通过AJAX来检查用户名,但我不能得到它的工作。 用户名可以随时服用,是否存在与否并不重要。

I am using the validation plugin and Laravel 4.2. I try to check the username via ajax, but I can't get it work. The username can always be taken, doesn't matter if exists or not.

我的第二个问题是,如果我使用的验证规则遥远,我无法提交表单。

My second issue is if I am using the validation rule remote, I can't submit the form.

有谁知道我在做什么错了?因为在铬日志中的所有优良,请求被发送,我可以看到调试消息。

Does anybody know what I am doing wrong? Because in the chrome log all is fine, the request is sent and I can see the debug messages.

<?php 
use App\Models\User;
class ValidationController extends BaseController {

public function getCheckUsername() 
{
    if(Request::ajax()) {
        $user = User::where('username', Input::get('username'))->get();
        if($user->count()) {
            return Response::json(array('msg' => 'true'));
        }
        return Response::json(array('msg' => 'false'));

    }

}


}

JS

$(document).ready(function()
{
$("form").validate({

rules: {
        username: {
                required: true,
                     rangelength:[3,255],
        remote: {
                url:"http://"+location.host+"/validation/checkusername",
                type: "get",
                success: function(msg){
                 if(msg.msg == 'true') {
                  console.log('exists');
                  return true;
                 }
                 console.log('doesnt exists');
                  return false;
                }

                },


                },
  messages: {
            username: {
                required: "Please Enter Username!",
                remote: "Username already in use!"
            }
        }
});
});

我也试图通过创建$ .validator.addMethod()一个自己的规则,但这种要么好好尝试一下工作。

I also tried to create an own rule via $.validator.addMethod(), but this doens't work either.

推荐答案

它看起来并不像你所发送的数据。尝试这个。注意POST请求。此外,我认为,dataFilter方法​​应该返回真正的

It doesn't look like you are sending the data. Try this. Note the post request. Also I believe the dataFilter method should return 'true'.

更新我也只是在你的PHP实现了逻辑发送该用户是否存在回真,因此在JavaScript中的逻辑应该是像这样:

Update I just also realized the logic in your php is sending back true if the user exists, therefore the logic in the javascript should be like so:

remote: {
    url: "http://"+location.host+"/validation/checkusername",
    type: "post",
    data: {
        username: function () {
            return $("input[name='username']").val();
        }
    },
    dataFilter: function (data) {
        var json = JSON.parse(data);
        if (json.msg == "true") {
            return "\"" + "That username is taken" + "\"";
        } else {
            return 'true';
        }
    }
}

这篇关于jQuery验证检查用户名与远程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆