简体   繁体   English

如何使用jQuery Validate插件检查记录是否存在?

[英]How should I check if record exists or not using jQuery Validate Plugin?

I am using jQuery Validate Plugin found from below URL 我正在使用从下面的URL找到的jQuery Validate插件

http://bassistance.de/jquery-plugins/jquery-plugin-validation/ http://bassistance.de/jquery-plugins/jquery-plugin-validation/

I just wanted to make a validation rule to check if the record exists in database or not. 我只是想制定一个验证规则,以检查记录是否存在于数据库中。 I also made ajax script like blow & added it using $.validator.addMethod but it is not working. 我还制作了像blow这样的ajax脚本,并使用$ .validator.addMethod添加了它,但是它不起作用。 can someone please suggest how to do this ? 有人可以建议如何做到这一点吗?

$.validator.addMethod("check_exists", function(value) {
$.ajax({
    type: "POST",
    url: "xyz.com/check_exists.php",
    data: $( "#frmEdit" ).serialize(),
        success: function(result){
                if(result=="exists")
                   return false;
                else
                   return true;
        },
});
}, 'This record is already exists');

Validation plugin has a built in remote option you provide a url to and the request will be made to server from within plugin. 验证插件有一个内置的remote选项,您可以提供一个URL,该请求将通过插件内的服务器发出。 For what you are doing there is no need to creat a whole new method 对于您正在做的事情,无需创建一种全新的方法

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

The problem you are running into is that (1) the AJAX call is asynchronous so the method is returning before the AJAX call completes and (2) the return statements within the callback handler return from the handler not the validation function. 您遇到的问题是(1)AJAX调用是异步的,因此该方法在AJAX调用完成之前返回,并且(2)回调处理程序中的return语句从处理程序而不是验证函数返回。 The simplest way to fix this is to use the remote validation method. 解决此问题的最简单方法是使用远程验证方法。 If you want to do it yourself, you need to have the AJAX call be synchronous ( async: false ) and capture the result into a variable that is returned from the function. 如果您想自己执行此操作,则需要使AJAX调用是同步的( async: false ),并将结果捕获到该函数返回的变量中。

$.validator.addMethod("check_exists", function(value) {
    var status;
    $.ajax({
        type: "POST",
        async: false,
        url: "xyz.com/check_exists.php",
        data: $( "#frmEdit" ).serialize(),
        success: function(result){
            status = result=="exists";
        },
    });
    return status;
}, 'This record is already exists');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM