Posts Tagged ‘web forms’

Form Validation using Prototype(no return false): How to cancel an event

Saturday, September 13th, 2008

I remember getting lost a few times back when I first started using Prototype. I was trying to implement some form validation, which is pretty easy with prototype, but ‘old habits’ were getting in my way. Coming from ‘plain old javascript’, I was accustomed to using ‘return false;’ to cancel a form submission, but when you’re trying to separate form from function(and thats really the whole point of events), you don’t necessarily want to put javascript into your html. e.g.:

<form onsubmit=’return myValidator();’>

First of all, it’s ugly. More importantly though, it mixes your javascript and your html, if you want to rename your validator function you now have to dip into the HTML code(which should probably live in a different file)… ew, divs. Since you’re using prototype you should be using prototype’s event management. Here’s a sample:

<form id=”myForm”…>

$(’myForm’).observe(’submit’, doValidation);
function doValidation(event) {
//do validation here
}

And, in order to stop the form from submitting you would use Prototype’s Event library again:

myEvent.stop();

This stops the submission event from ‘bubbling up(or down)’ to the Document Object and being submitted. This is our ‘return false;’

Putting it all together we get something like this:

<form id=”myForm”…>
<input id=”email”

$(’myForm’).observe(’submit’, doValidation);
function doValidation(submissionEvent) {
if($(’email’) && !(/^.+@.+\..+/.exec($(’email’).value))){
//not valid, let the user know.
submissionEvent.stop();
}
//do more validation here
}

..and there was much rejoicing. Our HTML and and javascript are separate, our lives are easier. Our new code also makes it clear that form submissions are actually events and that our validation function is a handler for that event.
Cheers!

Apparenly Ryan Campbell wrote on the same subject back in 2006, he claimed that Event.stop() didn’t work in Safari but as far as I know that’s no longer true.
Prototype’s api entry for event.stop.