我一直在研究JavaScript验证程序,但是由于某种原因,即使evalid通过了验证,evalid总是返回false……这是一个错误,好像evalid为false时,表单未提交。

function signup_validate()
    {
        document.getElementById("email_error").innerHTML = "";
        document.getElementById("password_error").innerHTML = "";
        evalid = false;
        pvalid = false;
        email = null;
        pass = null;
        confpass = null;
        email=document.forms["signup_form"]["email"].value.replace(/^\s+|\s+$/g, '');
        atpos=email.indexOf("@");
        dotpos=email.lastIndexOf(".");
        pass=document.forms["signup_form"]["pass"].value;
        confpass=document.forms["signup_form"]["confpass"].value;
            if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
            {
                document.getElementById("email_error").innerHTML = "<span class='required'>Email must be valid.</span>";
            }
            else
            {
                $.post('/resources/forms/signup.php',{email: email}, function(data){
                    if(data.exists){
                        document.getElementById("email_error").innerHTML = "<span class='required'>This email is already in use.</span>";
                    }
                    else
                    {
                        evalid = true;
                    }
                }, 'JSON');
            }
            if (pass!=""&&pass!=null&&confpass!=""&&confpass!=null&&confpass==pass)
            {
                pvalid = true;
            }
            else
            {
                document.getElementById("password_error").innerHTML = "<span class='required'>Both passwords must match and cannot be left blank.</span>";
            }
            alert(evalid);
            if (evalid == true && pvalid == true)
            {
                document.getElementById("signup_form").submit();
            }
            else
            {
                return false;
            }
        }


我可能错过了什么?

最佳答案

将“ evalid”设置为true的唯一时刻是在异步运行的函数内部。换句话说,到您将“ evalid”设置为true时,主要功能已经结束。

您可以尝试使用$.ajax代替$.post并使用参数async:false

尝试这样的事情:

$.ajax({
    type: 'POST',
    url: '/resources/forms/signup.php',
    data: {email: email},
    success: function(response){
        //your function here
    },
    dataType:'JSON',
    async:false
});

关于javascript - JavaScript验证错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13889174/

10-12 03:52