Archive

Posts Tagged ‘Form validation’

Check that form!

November 25th, 2009 James Barnsley No comments

So in a recent web project I decided to incorporate some fancy Javascript form-verification code. Thinking it would be a breeze, I started with a link to submit the form and run the Javascript function:

<a href=”javascript:submitForm()”>Send form</a>

After I made the Javascript function work I then realised I had no idea how tell the page to submit the form. I discussed this problem with a colleague and he told me I was doing it all wrong. Best practice is to have a normal submit button and link the Javascript function at the bottom of the form. In my case I was using PHP which detected if the form was ready to send an email or not, so the form’s action was left empty (action=”").

In the Javascript I referenced the form with:

var f = document.getElementById(“contact-form”);
f.onsubmit = submitForm;

var f = document.getElementById(“contact-form”);
f.onsubmit = submitForm;

This code is vital to make this work as it links the HTML form and the Javascript function together. Once the submit button is pressed, the Javascript function runs (I called it submitForm) and if it encounters and error it returns false. This tells the HTML that the submission was unsuccessful.

Long story short, Javascript can be run between clicking Submit and the actual submit process to decide if the form is valid. From there you can run the appropriate error message or proceed to the submit script. Still don’t get what I mean? Check out a live test version at: http://www.jamesbarnsley.co.nz/mbv/dev.