user5113176
user5113176

Reputation: 47

Javascript Validating username Length

I am trying to validate my username field and check if the username contains atleast 6 letters, if not then i show a pop up window indicating the same. But the alert command does not seem to work.

Following is the code:

<html>
<head>
<title> Webpage </title>
</head>
<script language="Javascript">
function validate()
{

if (username1.length < 6)
{
alert("Username must be atleast 6 charactrs long, Please Try Again");
}

}


</script>
<body>
<form>
<center>
 <fieldset>
<table cellspacin="5" cellpadding="5" border="0">

<tr>
<td>Username: </td>
<td align="left"><input type=="text" name="username1" maxlength="20" size="20">
</td>
</tr>

<tr>
<td> Password: </td>
<td align = "left"> <input type="text" name="password" maxlength="20" size="20">
</td>
</tr>

<tr>
<td> Please confirm your password: </td>
<td align = "left"> <input type="text" name="password1" maxlength="20"        size="20">
</td>
</tr>

<tr>
<td align="center"><input type="submit" value="Log in" onClick="validate()">
</td>
</tr>
</fieldset>
</table>

</center>
</form>
</body>
</html>

Upvotes: 1

Views: 7297

Answers (2)

user5113176
user5113176

Reputation: 47

Answer: I tried it this way it worked:

       <html>
       <head>
      <title> Webpage </title>
     </head>
      <script language="Javascript">
     function validate()
     {

     username2 =form1.username1.value

    if (username2.length < 6)
    {
    alert("Username must be atleast 6 charactrs long, Please Try Again");
    } 

   } 


  </script>
  <body> 
  <form name="form1">
   <center>
  <fieldset>
  <table cellspacin="5" cellpadding="5" border="0">

 <tr>
 <td>Username: </td>
 <td align="left"><input type=="text" name="username1" maxlength="20" size="20">
 </td>
 </tr>

 <tr>
 <td> Password: </td>
 <td align = "left"> <input type="text" name="password" maxlength="20" size="20">
 </td>
 </tr>

 <tr>
 <td> Please confirm your password: </td>
 <td align = "left"> <input type="text" name="password1" maxlength="20" size="20">
 </td>
 </tr>

 <tr>
  <td align="center"><input type="submit" value="Log in"  onClick="validate()">
 </td>
 </tr>
 </fieldset>
 </table>

 </center>
 </form>
 </body>
 </html>

Upvotes: 0

Olavi Sau
Olavi Sau

Reputation: 1649

You are trying to use the name element attribute as the id, which creates a global window property. Name does not do that however, you can use. You also aren't getting the value, you are trying to get the length on the element.

document.getElementsByName('username1')[0].value

Upvotes: 3

Related Questions