One of the most popular uses of Javascript is when it comes to validating user input on a form. The most hateful way, though, is by not using onsubmit. A number of times I come across code where someone uses an image in place of the submit button and uses the onclick event which will validate then submit the form. Yeauch! Very bad practice!
The first thing to do with the form is place the Javascript function in the onsubmit attribute for the form, e.g.
<form name="reg" method="post" onsubmit="return validateForm();"
The use of return lets the form submit when the function returns true. If the function does not return true (i.e. false) then the form will not submit - as shown below.
function validateForm(){
return false;
}
Getting a reference to the form is the next step. There are a number of ways to do this:
- document.forms[0]
- document.forms['reg']
- document.getElementById('reg') This will work when id is used on the form
- Passing an object reference through the onsubmit handler
My preference is number 5. Passing the reference is achieved using the this keyword. So the onsubmit handler will look like
<form name="reg" method="post" onsubmit="return validateForm(this);"
and the function header would be. The function also demonstrates how a field is accessed
function validateForm(formObj){
alert(formObj.username.value);
return false;
}
As you can see this is much more straightforward and is pretty much cross-browser compatible. This has been tested with IE (6 and 7), Firefox (2 and 3), Google Chrome and Safari (v3 and v4) on the PC. And also tested on the Mac with Firefox 2 and Safari 2.
To actually do things with the form, a good tutorial exists over at quirksmode.org.
Comments