Page 1 of 1

String Length

Posted: Mon Mar 29, 2010 11:36 am
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?

Re: String Length

Posted: Mon Mar 29, 2010 2:06 pm
by omniuni
Hm, would something like this work:

Code: Select all

<input type="text" onkeyup="if(this.value.length > 5){alert('over 5!');}"></input>

Re: String Length

Posted: Mon Mar 29, 2010 2:56 pm
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

Re: String Length

Posted: Tue Mar 30, 2010 12:01 pm
by Parmenion
Thanks both. I think I'll use what omniuni suggested as it works just as I want. :)