6

好吧,我放弃了。在尝试了内联函数、回调、返回参数的无尽排列之后,我仍然无法让它表现出我想要的样子。任何帮助,将不胜感激。

当前状态:除“checkEmail”错误消息外,一切正常。javascript 弹出窗口将正确的消息传达给用户,但该字段不会显示任何错误消息,无论处理程序返回 true 还是 false。

期望的结果是,如果来自 AJAX 调用的 JSON 有效负载不是 200,则弹出 Javascript 警报并使用适当的错误消息突出显示该字段为无效。目前,它会弹出警报,但不会将该字段标记为无效。

(对不起,这是 jQuery 1.7 + jquery.validation 插件)

JSON 响应:

我们的 JSON 响应负载如下所示:

{"message": "Email is not in use.", "code": 200, "email": "test-39485787@mailinator.com"}

或者

{"message": "Duplicate email address detected", "code": 401}

编码

<html>

<head>
<script>

// You'd think this should be false, but no
// Also it apparently needs to be a quoted 
// string: http://stackoverflow.com/a/11496502/814669
var checkEmailStatus = "true";

// Success Handling
checkEmailSuccess = function(data, textStatus, jqXHR) {
    checkEmailStatus = "true";
    switch (data.code) {
        case 200:
            checkEmailStatus = "false"; // Nothing set here matters
            return false; // Return valued from here don't matter
        case 401:
            alert("Sorry, our system has detected that an account with this email address already exists.");
            break;
        case undefined:
            alert("An undefined error occurred.");
            break;
        default:
            alert("An undefined error occurred.");
            break;
    }
    return checkEmailStatus;
};


// Error Handling
checkEmailError = function(jqXHR, textStatus, errorThrown) {
    if (jqXHR.status == 404) {
        alert("Could not find the API Server (404). We apologize for the inconvenience.");
    } else {
        alert("Terrible things have happened" + textStatus);
    }
    return false;
};


// The Validator
jQuery.validator.addMethod("checkEmail", function(value, element) {

    $.ajax({
        type: "POST",
        cache: "false",
        async: "false",
        url: "/json/checkEmail",
        dataType: "json",
        data: {
            email: function() {
                return $("email").val();
            }
        },
        success: checkEmailSuccess,
        error: checkEmailError
    });

    // Seems checkEmailStatus value never gets changed:
    return checkEmailStatus;

}, "Email Address Problem");


// The Binding
$(document).ready(function(){
    $('#MyForm').validate({
        onfocusout: false,
        onkeyup: false,
        rules: {
            "email": {
                required: true,
                minlength: 2,
                maxlength: 42,
                email: true,
                checkEmail: true
            }
        }
    });
});

</script>
</head>

<body>

    <!-- the Form -->
    <form id="MyForm">
        <input type="text" name="email"/>
        <input type="submit" name="submit"/>
    </form>

</body>
</html>
4

3 回答 3

16

这里的正确答案是确实使用“remote”选项,但使用“dataFilter”进行所有响应处理:

checkEmailSuccess = function(response) {
    switch (jQuery.parseJSON(response).code) {
        case 200:
            return "true"; // <-- the quotes are important!
        case 401:
            alert("Sorry, our system has detected that an account with this email address already exists.");
            break;
        case undefined:
            alert("An undefined error occurred.");
            break;
        default:
            alert("An undefined error occurred");
            break;
    }
    return false;
};

"email": {
    required: true,
    minlength: 2,
    maxlength: 42,
    email: true,
    remote: {
        url: "/json/checkEmail",
        type: "POST",
        cache: false,
        dataType: "json",
        data: {
            email: function() { return $("#email").val(); }
        },
        dataFilter: function(response) {
            return checkEmailSuccess(response);
        }
    }
},
于 2013-06-07T23:50:33.393 回答
3

addMethod 期望立即得到真/假响应,并且您正在执行 AJAX 调用,这是一个异步操作,因此变量 checkEmailStatus 将返回其初始值。请查看“远程”验证,这是您需要的:

http://jqueryvalidation.org/remote-method/

更新:我刚刚注意到 async = false。尽量避免该选项。它降低了用户体验。

试试这个:

$('#MyForm').validate({
    onfocusout: false,
    onkeyup: false,
    rules: {
        "email": {
            required: true,
            minlength: 2,
            maxlength: 42,
            email: true,
            //checkEmail: true
            remote:{
                url: "/json/checkEmail", //make sure to return true or false with a 200 status code
                type: "post",
                data: {
                    email: function() {
                        return $("email").val();
                    }
                }
            }
        }
    }
});
于 2013-06-07T21:28:46.413 回答
0

如果你想使用实际的 http 响应代码,你可以使用 $.ajax 调用的错误函数,它将在验证插件中工作。

remote: {
    url: "/json/checkEmail",
    type: "POST",
    cache: false,
    dataType: "json",
    data: {
        email: function() { return $("#email").val(); }
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.status);
        alert(textStatus);
        alert(errorThrown);
    }
于 2014-01-22T23:01:54.243 回答