Javascript form validation – oldie but goodie

11 05 2007

I really like what javascript can do, but I hate working with it. My problem is I know just enough to be dangerous, as the saying goes, and I often am.

I have had to do some different form validation over the years and the following code works pretty well out of the box. The snippet below will validate everything, and with some adjustments will validate as you see fit. My guess is there are better, more condensed, ways to get this done (I stumbled across this bit of code several years ago) but it still works well for me and seems to run fine in IE and Firefox.

If I’m performing some gross injustice by using this code please say so in the comments along with what I should be using, if you would be so kind.

function validateForm (form) {
for (var e = 0; e < form.elements.length; e++) {
var el = form.elements[e];
if (el.type == 'text' || el.type == 'textarea' ||

el.type == 'password' || el.type == 'file' ) {

if (el.value == '') {

alert('Please fill out the text field ' + el.name);

el.focus();

return false;

}

}

else if (el.type.indexOf('select') != -1) {

if (el.selectedIndex == -1) {

alert('Please select a value of the select field ' + el.name);

el.focus();

return false;

}

}

else if (el.type == 'radio') {

var group = form[el.name];

var checked = false;

if (!group.length)

checked = el.checked;

else

for (var r = 0; r < group.length; r++)

if ((checked = group[r].checked))

break;

if (!checked) {

alert('You must select an option to continue');

el.focus();

return false;

}

}

else if (el.type == 'checkbox') {

var group = form[el.name];

if (group.length) {

var checked = false;

for (var r = 0; r < group.length; r++)

if ((checked = group[r].checked))

break;

if (!checked) {

alert('Please check one of the checkboxes ' + el.name);

el.focus();

return false;

        }

      }

    }

  }

  return true;

}