String Length

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

String Length

Post by Parmenion »

Hi guys,

I don't know much about JavaScript but having a go at validating form input. I can check whether the user has entered anything but struggling with string length.

The code:

[text]
<form action="register.php" onsubmit="return validate_registration(this);" method="post">
<b>Password:</b><br />
<input type="password" size="20" name="password"> <br /><br />
<input type="submit" name="submit" value="Continue">
</form>
[/text]

[text]
function validate_registration (field)
{
if (field.password.value.length > 40)
{
alert ("Your password must be 40 characters or less.");
field.password.focus();
return false;
}
else
{
return true;
}
}
[/text]

Any idea why it isn't working?
User avatar
omniuni
Forum Regular
Posts: 738
Joined: Tue Jul 15, 2008 10:50 pm
Location: Carolina, USA

Re: String Length

Post by omniuni »

Hm, would something like this work:

Code: Select all

<input type="text" onkeyup="if(this.value.length > 5){alert('over 5!');}"></input>
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: String Length

Post by califdon »

I'm not familiar with your object model (like, "field.password.value.length"). I use the function getElementById():

Code: Select all

...
<input type='text' name='password' id='password' />
...
fld=document.getElementById('password');
... 
whatever ... fld.length
Parmenion
Forum Commoner
Posts: 35
Joined: Sat Dec 12, 2009 8:29 am

Re: String Length

Post by Parmenion »

Thanks both. I think I'll use what omniuni suggested as it works just as I want. :)
Post Reply