0

In the following code, the error message is generated regardless of whether checkEMailExists returns true or false. What am I doing wrong? The ajax call is working properly.

$().ready(function () {

$.validator.addMethod("checkEmailExists",
        function (value, element) {
            $.when(checkEmail()).done(function (response) {
                console.log((response == 1 ? "true" : "false"));
                return response == 1; // returns true if response is 1, false otherwise
            });
        },
        "This email address is registered"
        );

$("#loginform").validate({
    rules: {
        email: {
            required: true,
            checkEmailExists: true
        }
    },
    messages: {
        email: {
            required: "Please enter a valid email address",
            checkEmailExists: "This email address is already registered"
        }}
});

function checkEmail() {
    var email = $("#email").val();
    var data = {email: email};
    return $.ajax({
        type: "POST",
        url: "http://localhost/check_email/check_email.php",
        data: data
    });
}
Sparky
  • 98,165
  • 25
  • 199
  • 285
dru37
  • 199
  • 1
  • 11
  • There is no need to write a custom method. To check if a username already exists, use the `remote` method. See: http://stackoverflow.com/questions/16577120/jquery-validate-remote-method-usage-to-check-if-username-already-exists – Sparky Dec 28 '16 at 00:20
  • It looks like your logic is backwards. In the custom method, only `return true` to PASS validation. – Sparky Dec 28 '16 at 00:23

0 Answers0