jQuery 使用jquery验证的远程功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10903100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:55:53  来源:igfitidea点击:

Using the remote function of jquery validation

jqueryjquery-validate

提问by Jeff Davidson

I'm trying to figure out how I can turn this:

我想弄清楚如何解决这个问题:

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

into something close to this:

接近这个的东西:

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

            }
        }

However I'm having a hard time finishing it off. What I want is instead of the alert to have it display the error message but I can set the message inside the actual jquery validation messages.

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

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

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

UPDATE:

更新:

For some reason its not doing it as a POST its doing it as a GET request and not sure why. Here's the updated code:

出于某种原因,它没有将其作为 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!'
                        }
                    }
                }

            }
        },

UPDATE 2:

更新 2:

Now I'm getting somewhere I'm back to getting the POST request. I'm getting two more problems. One of which is the fact that for another POST request to be done the user has to refresh the form. And the last problem is that if the returned username is found it DOES NOT show the error message.

现在我到达某个地方,我又回到了 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!'
                        }
                    }
                }

            }
        },

UPDATE:

更新:

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

UPDATE 4:

更新 4:

Controller:

控制器:

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

采纳答案by chris

Well I dunno bout your plugin concept specifically but I gather you want it to check to see with that plugin if the username is greater than 6 or less than 12. Which from your core example with jQuery without the plugin it would be as simple as adding one little if-else to the concept.

好吧,我不知道你的插件概念具体是什么,但我猜你希望它检查使用该插件查看用户名是否大于 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');
    }
});

回答by Andrew Whitaker

The easiest way to accomplish this is to simply return true, an error message as a string, or falsefrom your server-side resource. According to the jQuery validate documentation for remote:

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

The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.

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

This means if you can change your server-side code to return truein the event of successful validation or an error message ("username already in use") in the event of unsuccessful validation, you could just write the following remote rule:

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

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

You could also simply return trueor falsefrom your server-side resource and define the error message on the client. In that case you would have the above rule and then a property in the messagesobject:

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

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

回答by qiqe.f

I know it's too late, but this could help other people.

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

The remote method is meant to recieve a Json string, so your server side should be returning something like this to the method...

远程方法是为了接收一个 Json 字符串,所以你的服务器端应该向方法返回这样的东西......

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

This is an example of the JS code that I wrote while trying to validate user's nickname.

这是我在尝试验证用户昵称时编写的 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"
                }
            }
        });});

Hope it helps someone, it helped me.

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

回答by damajj

I realize this is old but I had a hard time getting this working as well and wanted to share what worked for me.

我意识到这很旧,但我也很难让它正常工作,并想分享对我有用的东西。

Client-Side form validation code:

客户端表单验证代码:

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

Server-Side code for ADIDValidation.cshtml (I'm using Razor webpages):

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

回答by Sukhwinder Sodhi

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

You need to pass username

您需要传递用户名

回答by Sumit Kumar Gupta

I think I am too late to reply. but our code is very easy for all

我想我已经来不及回复了。但我们的代码对所有人来说都非常简单

Validation Code

验证码

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

Controller Code

控制器代码

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

Model Code

型号代码

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

回答by Deepika Sachdeva

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
    }

回答by Dileep CK

I needed to do remote validation in a rails project recently and struggled to send the correct response from server side if the input is invalid. At the end, the solution was quite simple.

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

If the server side check returns true, you can send true or "true", else you can return any string like "The email already exists" or "Email does not have valid MX records". This string will be displayed as the validation message on the form. The only catch is that the message string returned from server side should be valid JSON and should be in this format - ["The email already exists"].

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

Some explanation on how I debugged and found the solution: Please see below the remote method in jquery.validate.js. I had added log statements and an error function to the ajax call to debug. When I returned a normal string from server side, a jQuery.parseJson error was thrown.

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