Domanda

Ho aggiunto un metodo di convalida personalizzato per convalidare una password. Tuttavia, non importa se il JSON che ottengo è:

{"success":true}

o:

{"success":false}

Il campo password non è mai valido.

$(document).ready(function() {
    // Ad custom validation
    $.validator.addMethod('authenticate', function (value) { 
    $.getJSON("./json/authenticate.do",{ password: value},function(json) { 
                return (json.success == true) ? true : false;}
            ); 
    }, 'Wrong password');

    $('form#changePasswordForm').validate({
            rules: {
                 repeat_new_password: { equalTo: "#new_password"    },
                 password :  {authenticate: true}
        }, submitHandler: function(form) {
                    $(form).ajaxSubmit( {
                            dataType: "json", 
                            success: function(json) {
                            alert("foo");
                    }
        });                     
    }
});         
});

Qualche idea, cosa sto facendo di sbagliato?

È stato utile?

Soluzione

Quello che fai di sbagliato è che quando aggiungi il tuo metodo personalizzato non ne restituisci mai vero o falso. Lo restituisci nel callback Ajax.

$.validator.addMethod('authenticate', function (value) { 
    $.getJSON("./json/authenticate.do",{ password: value }, function(json) { 
        // This return here is useless
        return (json.success == true) ? true : false;
    }); 
    // You need to return true or false here...
    // You could use a synchronous server call instead of asynchronous
}, 'Wrong password');

Invece di aggiungere un metodo personalizzato, è possibile utilizzare la funzione remote :

$('form#changePasswordForm').validate({
    rules: {
        repeat_new_password: { 
            equalTo: "#new_password" 
        },
        password : { 
            // This will invoke ./json/authenticate.do?password=THEVALUE_OF_THE_FIELD 
            // and all you need to do is return "true" or "false" from this server script
            remote: './json/authenticate.do' 
        }
    }, 
    messages: { 
        password: { 
            remote: jQuery.format("Wrong password")
        }
    },
    submitHandler: function(form) {
        $(form).ajaxSubmit({
            dataType: "json", 
            success: function(json) {
                alert("foo");
            }
        });                     
    }
});   

Puoi verificarlo in azione qui .

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top