获取未定义的值而不是true或false

时间:2014-02-17 11:53:29

标签: jquery

我正在使用jquery进行表单验证,我编写了一个函数来检查电子邮件是否已经存在。当我在函数内部发出警报时,我得到一个true或false值但是当我调用该函数时,我得到一个未定义的值。输入电子邮件地址后,我需要一个真值或假值,有人可以帮助我吗?

我添加了我的代码:Here

HTML:

    <div style="display: none;" id="dialog-form" title="Create new master admin">
    <div class="validateTips">All form fields are required.</div>
    <form id="target" method="post">
        <fieldset>
            <table width="100%">
                <tr>
                    <td colspan="3">Please complete the form to create a new master admin (All form fields are required)</td>
                </tr>
                <tr>
                    <td height="20px"></td>
                </tr>
                <tr>
                    <td width="150px">Name</td>
                    <td colspan="2" valign="middle">
                        <input type="text" name="name" id="name" size="20" class="text ui-widget-content ui-corner-all" />
                    </td>
                </tr>
                <tr>
                    <td>Surname</td>
                    <td colspan="2">
                        <input type="text" name="password" id="password" size="20" class="text ui-widget-content ui-corner-all" />
                    </td>
                </tr>
                <tr>
                    <td>Email</td>
                    <td width="200px">
                        <input type="text" name="email" id="email" size="20" class="text ui-widget-content ui-corner-all" />
                    </td>
                    <td align="left"><span id="availability_status"></span>
                    </td>
                </tr>
                <tr>
                    <td>Cellphone</td>
                    <td colspan="2">
                        <input type="text" name="cellphone" id="cellphone" size="20" class="text ui-widget-content ui-corner-all" />
                    </td>
                </tr>
                <tr>
                    <td align="center" colspan="3">(A random username and password will be sent to the email provided)</td>
                </tr>
            </table>
        </fieldset>
    </form>
</div>
<button id="create-user">Create new user</button>

Jquery的:

$(function () {
    var name = $("#name"),
        email = $("#email"),
        surname = $("#password"),
        cellphone = $("#cellphone"),
        allFields = $([]).add(name).add(email).add(surname).add(cellphone),
        tips = $(".validateTips");

    function updateTips(t) {
        tips.text(t)
            .addClass("ui-state-highlight");
        setTimeout(function () {
            tips.removeClass("ui-state-highlight", 1500);
        }, 500);
    }
    // Min max Length of field 
    function checkLength(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass("ui-state-error");
            updateTips("Length of " + n + " must be between " + min + " and " + max + ".");
            return false;
        } else {
            return true;
        }
    }

    // Check empty fields
    function checkEmpty(o, n) {
        if (o.val() == "") {
            o.addClass("ui-state-error");
            updateTips("please fill in " + n + ".");
            return false;
        } else {
            return true;
        }
    }

    // Check email
    function checkEmail() {
        //if ( o.val() == "") {
        var email = $("#email").val();
        var bValid = true;
        $.ajax({ //Make the Ajax Request
            type: "POST",
            url: "master_admin_setup_submit.php", //file name
            data: "email=" + email, //data
            success: function (server_response) {
                //                                alert(server_response);
                if (server_response == '1') //if ajax_check_username.php return value "0"
                {
                    $("#availability_status").html('<img src="../images/not_available.png" align="absmiddle"> <font color="red">Email already used</font>');
                    //add this image to the span with id "availability_status"
                    bValid = false;
                    return (bValid);
                } else {
                    bValid = true;
                    //alert(server_response);
                    return (bValid);
                }
                //alert(checkEmail());



                //o.addClass( "ui-state-error" );
                //updateTips( "please fill in " + n + "." );
                //return false;
                //} else {
                //return true;
                //}
            }
        });
    }

    function checkRegexp(o, regexp, n) {
        if (!(regexp.test(o.val()))) {
            o.addClass("ui-state-error");
            updateTips(n);
            return false;
        } else {
            return true;
        }
    }
    $("#dialog-form").dialog({
        autoOpen: false,
        width: 550,
        modal: true,
        resizable: false,
        buttons: {
            "Create master admin": function () {

                var bValid = true;
                allFields.removeClass("ui-state-error");
                bValid = bValid && checkLength(name, "username", 3, 16);
                bValid = bValid && checkLength(email, "email", 6, 80);

                bValid = bValid && checkEmail();
                alert(bValid);
                bValid = bValid && checkLength(surname, "surname", 5, 16);
                bValid = bValid && checkEmpty(cellphone, "cellphone");

                //  bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                bValid = bValid && checkRegexp(email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com");
                //bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
                if (bValid == true) {
                    $.post('master_admin_setup_submit.php', $('#target').serialize(), function (result) {
                        //                                    alert(result);
                        if (result === "1") {
                            $(function () {
                                $("#dialog-email").dialog({
                                    modal: true,
                                    buttons: {
                                        Ok: function () {
                                            $(this).dialog("close");
                                        }
                                    }
                                });
                            });

                        } else {
                            $(function () {

                                $("#dialog-message").dialog({
                                    modal: true,
                                    buttons: {
                                        Ok: function () {
                                            $(this).dialog("close");
                                        }
                                    }
                                });

                            });
                            // Reset form
                            $('#target')[0].reset();
                            // Close main dialog
                            $("#dialog-form").dialog("close");
                        }
                    });
                }
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        }
    });
    $("#create-user")
        .button()
        .click(function () {
        $("#dialog-form").dialog("open");
    });
});

1 个答案:

答案 0 :(得分:0)

您的checkEmail()功能存在问题。它本身不会返回任何内容,因此如果在计算公式bValid = bValid && checkEmail();之前bValid为真,则这将是未定义的。

如果在函数内部调用$.ajax(),则默认情况下是异步的,因此最有可能在脚本验证后您将获得服务器返回的数据您的数据将完成工作。换句话说,您的函数不会在$.ajax()上停止并等待结果,但会进一步运行,并且正在并行处理请求。您必须弄清楚如何使您的脚本等待服务器返回的数据。如果您只使用一个ajax验证器,它只需调用一个完成数据验证的函数,如果成功,则将数据发布到服务器。否则你必须意识到,结果可能以随机顺序出现在你的函数中,也必须要管理 我希望它有所帮助。