views:

18

answers:

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

<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>

when i click submit now, it does not match the pattern, but rather cycles through the else if statements although it never comes up with "please include a capitalized letter" but only the other two. what am i doing wrong?

+2  A: 

All of these:

if (user_name != pattern){ ...

Should be more like this:

if (pattern.test(user_name)){ ...
Michael Haren
plus what floatless said... I'd suggest investing in a good browser debugger. It will save you hours of headache. If you use Chrome, hit `ctrl-shift-i`; if you use Firefox, get the firebug extension; if you use IE8, hit `F12`
Michael Haren
+2  A: 

This is wrong:

document.getElementById(error_message)

You should add single or double quotes to the argument:

document.getElementById("error_message")
floatless
Same thing for `(user_name)`
Michael Haren