Frage

Ich habe eine benutzerdefinierte Validierungsmethode ein Passwort zu validieren. Aber es spielt keine Rolle, ob die JSON ich erhalte, ist:

{"success":true}

oder:

{"success":false}

Das Feld Passwort validiert nie.

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

Jede Idee, was ich tue falsch?

War es hilfreich?

Lösung

Was Sie falsch machen, ist, dass, wenn Sie Ihre eigene Methode hinzufügen, die Sie nie davon wahr oder falsch zurück. Sie kehren sie in dem Ajax-Rückruf.

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

Statt eine eigene Methode des Hinzufügens Sie die Fern Funktion nutzen könnten :

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

Sie können es in Aktion überprüfen hier .

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top