PDA

View Full Version : Quick JavaScript Validation Question



centenial
07-21-2006, 10:13 PM
Hi,

I have this code:


function validate_form ( ) {
valid = true;
if ( document.listing.l_id.value == "" ) {
alert ( "Please enter a Listing ID!" );
valid = false;
}

if ( document.listing.a_id.selectedIndex == 0) {
alert ( "Please select an Agent!" );
valid = false;
}

if ( document.listing.category.selectedIndex == 0) {
alert ( "Please select an Category!" );
valid = false;
}

if ( document.listing.price.value == "" ) {
alert ( "Please enter a Price!" );
valid = false;
}

if ( document.listing.price_range.selectedIndex == 0) {
alert ( "Please select a Price Range!" );
valid = false;
}

if ( document.listing.town.selectedIndex == 0) {
alert ( "Please select a Town!" );
valid = false;
}

return valid;
}

I just want to add one last piece, which would do this:


if (valid == "true") {
alert ( "The Form Validated Successfully!" )
}
For some reason that isn't working... can anyone help please?

Twey
07-21-2006, 10:25 PM
The string "true" and the boolean value true are two very different values.

Be careful with global variables. Wherever possible, you should declare your variables with as little scope as possible, by using the var keyword.

Forms aren't necessarily available as properties of the document object, nor elements as properties of their form. You should use the forms and elements collections instead.

There is also quite a lot of code with no real point to it, and those repetitive popups will annoy users.

I would write it like this:
function validate_form ( ) {
var errors = '',
f = window.document.forms['listing'].elements;
if ( f.l_id.value === "" )
errors += "Please enter a Listing ID!\n";

if ( f.a_id.selectedIndex === 0 )
errors += "Please select an Agent!\n";

if ( f.category.selectedIndex === 0 )
errors += "Please select an Category!\n";

if ( f.price.value === "" )
errors += "Please enter a Price!\n";

if ( f.price_range.selectedIndex === 0 )
errors += "Please select a Price Range!\n";

if ( f.town.selectedIndex === 0 )
errors += "Please select a Town!";

if ( errors === "" ) {
window.alert( "The Form Validated Successfully!" );
return true;
} else {
window.alert( "Validation Failed:\n\n" + errors );
return false;
}
}However, there seems to be a common theme here, and I suspect that if I knew the layout of your form, it could be shortened much further.