[thelist] javascript form validation help

Ken Snyder kendsnyder at gmail.com
Wed Jun 11 13:08:12 CDT 2008


EvoltList at no-pun.com wrote:
> ...
>
> I have a couple radio button groups wherein if one button is checked, 
> validation then is required for associated form fields.  I have included my 
> _incorrect_ approach within, just so you see what I am trying to accomplish.
>
> <script language="javaScript" type="text/javascript">
> function validate_required(field,alerttxt)
> {
> with (field)
> {
> if (value==null||value=="")
>   {alert(alerttxt);return false;}
> else {return true;}
> }
> }
> ...
> Merci beaucoup!
> Greta 
>
>   
You'll need to iterate through a radio group to find out if any are 
checked.  See below for examples. Checkboxes can be verified in an 
identical manner, so you might want to name the function 
"validate_required_checkable". Also note that these functions do no 
error checking, so make sure you pass in the correct argument types 
(e.g. DOM Elements).

- Ken


function validate_required_radio(field,alertxt) {
  var radioGroup = field.form.elements[field.name];
  for (var i = 0; i < radioGroup.length; i++) {
    if (radioGroup[i].checked) {
      return true;
    }
  }
  alert(alerttxt);
  return false;
}

OR

function validate_required_radio(form,fieldName,alertxt) {
  var radioGroup = form.elements[fieldName];
  for (var i = 0; i < radioGroup.length; i++) {
    if (radioGroup[i].checked) {
      return true;
    }
  }
  alert(alerttxt);
  return false;
}

ALSO

function validate_required_select(field,alerttxt) {
  if (!field.options[field.selectedIndex].value) {
    alert(alerttxt);
    return false;
  } else {
    return true;
  }
}





More information about the thelist mailing list