Javascrippt在验证用户名后不重定向用户

时间:2018-11-10 14:59:03

标签: javascript html html5

<html>
<head>
</head>
    <body>

    <script>
        function myFun(){

            var correct_way = /^[A-Za-z0-9]+$/;

            var a = document.getElementById("User_Name").value;

            if(a=="") {
                document.getElementById("Message").innerHTML="Please enter a username.";
                return false;
            }
            if(a.length<5){
                document.getElementById("Message").innerHTML="Please enter a username with 5 or more characters";
                return false;
            }
            if(a.match(correct_way))
                document.location.href = "test1.html";
                else{
                document.getElementById("Message").innerHTML="Please enter a username with only letters and integers";
                return false;
            }


        }
    </script>

    <form onsubmit="return myFun()">
    <input type="text" id="User_Name" value=""></input>
    <br></br>
    <span id="Message">  </span> 
    <br></br>
    <input type="submit" value="Submit"></input>
    </form>
    </body>

</html>

您好,我已经创建了一个用户名验证码。验证确实有效,但是用户没有重定向到“ test1.html”文档。它们都在同一个文件夹中。检查验证后,如何使它重定向?

1 个答案:

答案 0 :(得分:1)

您应该在函数true的结尾处返回myFun

HTML

<form action="test1.html" onsubmit="return myFun()">
<input type="text" id="User_Name" value="" />
<span id="Message">  </span> 
<input type="submit" value="Submit" />
</form>

更新的代码

function myFun(){
        var correct_way = /^[A-Za-z0-9]+$/;

        var a = document.getElementById("User_Name").value;

        if(a=="") {
            document.getElementById("Message").innerHTML="Please enter a username.";
            return false;
        }
        if(a.length<5){
            document.getElementById("Message").innerHTML="Please enter a username with 5 or more characters";
            return false;
        }
        if(a.match(correct_way)){
              alert("Sucessful Login, welcome to BREAKOUT!");

        }
            else{
            document.getElementById("Message").innerHTML="Please enter a username with only letters and integers";
            return false;
        }

    return true;    
    }

jsFiddle演示-http://jsfiddle.net/h67q09mp/