我无法通过onsubmit按钮将警告发布在表单底部的

我无法通过onsubmit按钮将警告发布在表单底部的

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>Form</title>
<script type="text/javascript">
function isValidUsername() {
    var user_name = document.getElementById("user_name");
    var pattern =/^[A-Za-z0-9]{8,15}/g;
    var patternreq_1 = /[A-Z]/g;
    var patternreq_2 = /[0-9]/g;

    if (pattern.test(user_name)){
        document.getElementById("error_message").innertext ="";
        return true;
    }

    else if (patternreq_1.test(user_name)==false && patternreq_2.test(user_name)==false){
            document.getElementById("error_message").innerText =
                "*Please include a capitalized letter and a number in your user name.";
            return false;
    }
    else if (patternreq_1.test(user_name)==false && patternreq_2.test(user_name)==true){
            document.getElementById("error_message").innerText =
                "*Please include a capitalized letter in your username.";
            return false;
    }
    else if (patternreq_1.test(user_name)==true && patternreq_2.test(user_name)==false){
            document.getElementById("error_message").innerText =
                "*Please include a number in your username.";
                return false;
    }
    else if (user_name.length<8){
            document.getElementById("error_message").innerText =
                "*Please include at least eight letters in your username.";
                return false;
    }

}
 </script>
</head>


<body>

<form  method="post" name="contact_form"  onSubmit="return isValidUsername()">
    <h1>Please Enter Your Name</h1>
    <p>Your Name: <input type="text" name="user_name" id="user_name"></p>
    <p><input type="submit" name="send" value="Submit"></p>
    <p id="error_message" value="Use InnerText">&nbsp;</p>
</form>


</body>
</html>


当我单击立即提交时,它与模式不匹配,而是循环遍历else if语句,尽管它永远不会出现“请包含大写字母”,而只会出现另外两个。我究竟做错了什么?

最佳答案

所有这些:

if (user_name != pattern){ ...


应该更多like this

if (pattern.test(user_name)){ ...

关于javascript - 我无法通过onsubmit按钮将警告发布在表单底部的<p>中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3368176/

10-09 23:21