Need help with form input text validation

0 views
Skip to first unread message

Matt Wilson

unread,
Dec 9, 2006, 9:03:52 AM12/9/06
to TurboGears
This is probably a trivial problem. I have a textarea input box in a
form. I want to trigger some javasscript code when the user types too
much into the box.

For example, once the user types 101 characters, I'd like to pop up an
alert that says "You have typed more than the maximum allowed!"

How can I do this?

TIA

Matt

Diez B. Roggisch

unread,
Dec 9, 2006, 10:06:33 AM12/9/06
to turbo...@googlegroups.com

You need to attach a function to the input elements onkeyup event, like this:

function validate_input(event) {
if(event.target().value.length > 100) {
alert("you typed more than 100 characters");
}
}

MochiKit.Signal.connect(my_form.elements['elementname'], 'onkeyup',
validate_input);

But you are aware that the html input controls have a limit property
themselves, called "maxlength".

Diez

Christopher Arndt

unread,
Dec 10, 2006, 5:29:42 AM12/10/06
to turbo...@googlegroups.com
Diez B. Roggisch wrote:
> On Saturday 09 December 2006 15:03, Matt Wilson wrote:
>>For example, once the user types 101 characters, I'd like to pop up an
>>alert that says "You have typed more than the maximum allowed!"
>
> You need to attach a function to the input elements onkeyup event, like this:
>
> function validate_input(event) {
> if(event.target().value.length > 100) {
> alert("you typed more than 100 characters");
> }
> }
>
> MochiKit.Signal.connect(my_form.elements['elementname'], 'onkeyup',
> validate_input);
>
> But you are aware that the html input controls have a limit property
> themselves, called "maxlength".

Yes, but textarea elements don't seem to have such an attribute:

http://www.w3.org/TR/html401/interact/forms.html#h-17.7

If you need this, instead of popping up an annoying alert box, you could
set a visible counter on each keyup instead, that shows how many
characters are left and suppress further input if it exceeds the limit:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Counter test</title>

<script type="text/javascript" src="MochiKit.js"></script>

<script type="text/javascript">
var maxlength=100;

function count_input(e) {
if (e)
var text = e.src();
else
var text = $('text');
var chars_left = maxlength - text.value.length;
if (chars_left >= 0)
$('counter').value = chars_left;
else if (e) {
text.value = text.value.slice(0, maxlength);
e.stop();
}
}
connect(window, 'onload',
function() {
connect($('text'), 'onkeyup', count_input);
count_input();
}
);
</script>

</head>
<body>

<textarea id="text" cols="30" rows="4"></textarea><br />
Chars left: <input type="text" id="counter" size="4" readonly />

</body>
</html>

HTH, Chris

Reply all
Reply to author
Forward
0 new messages