简体   繁体   中英

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

I am using jQuery Validate Plugin found from below URL

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. 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. For what you are doing there is no need to creat a whole new method

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. 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.

$.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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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