使用jquery验证的远程功能

时间:2012-06-05 18:49:26

标签: jquery jquery-validate

我正在试图弄清楚如何解决这个问题:

$('#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;
    }        
}

MODEL:

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

8 个答案:

答案 0 :(得分:19)

实现此目的的最简单方法是简单地从服务器端资源返回true,错误消息作为字符串或false。根据{{​​3}}:

  

响应被评估为JSON,对于有效元素必须为true,   并且可以是任何false,undefined或null对于无效元素,使用   默认消息;或者一个字符串,例如。 “这个名字已经被拿走了,试试吧   peter123而不是“显示为错误消息。

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

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

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

messages: {
    username: {
        remote: "username already in use"
    }
}

答案 1 :(得分:7)

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

远程方法是为了接收一个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"
                }
            }
        });});

希望它对某人有所帮助,它帮助了我。

答案 2 :(得分:4)

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

客户端表单验证码:

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

答案 3 :(得分:1)

rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: 'register/isUsernameAvailable',
         }
        }

您需要传递用户名

答案 4 :(得分:0)

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

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

关于我如何调试并找到解决方案的一些解释: 请参阅下面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";
}

答案 5 :(得分: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;
        }
    }

答案 6 :(得分: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
    }

答案 7 :(得分:-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');
    }
});