[thelist] Stopping a user submitting a form from the address bar using JS.

.jeff jeff at members.evolt.org
Sat Dec 14 12:25:43 CST 2002


> From: Craig
> I've got a form on a page that uses JavaScript to
> validate the input.  This form is submitted with a
> button calling a JS function:
> <input type="button"
>        value="Submit"
>        onClick="check(form,form.elements.length);">

Bad idea.  Move the check() function call to the onsubmit event handler.
preface it with a return statement:

onsubmit="return check(this, this.form.elements.length)"

(the "this.form.elements.length" is redundant really as you could do that
from the function now that you have the object reference to it -- "this")

> The button is not a 'submit' button because after the
> script has validated the input, the script itself
> submits the form.

please don't do it this way.  instead, design your check() function to
return a boolean of true or false back to the event handler.  you can read
more about cancelable event handlers and the return statement by reading an
article i wrote on the submit:

JavaScript: The Point of No Return?!

you might also benefit from reading a couple of other articles i wrote:

Forms & JavaScript Living Together in Harmony

Links & JavaScript Living Together in Harmony

> However, if I open up this page in a browser (IE6) [...]

fwiw, *any* browser that supports javascript will allow the user to do what
you're describing, it's not an ie6-only thing.

> and type 'javascript:document.forms[0].submit()'
> (without the '), it will bypass the validation and
> submit the form.  How can I stop this?

you can't -- at all.  the submit() method is designed to directly submit the
form without triggering any event handlers.  so, no amount of client side
scripting is going to keep users from doing that.  if you want to guarantee
the data is validated, you've gotta do it on the server as well.  this will
also keep people from saving the page with your form to their harddrive,
removing the html, and submitting it from there.  if you have no server side
validation, then they can do as they please.

good luck,


jeff at members.evolt.org

More information about the thelist mailing list