PDA

View Full Version : Validate a form only if certain conditions are met


svennie12
05-09-2008, 04:06 PM
Hi,

Wondering if you can direct me on how to start this. This is an event registration form. If someone clicks Yes I will attend (radio button), then they should proceed to fill out the form (and this form should be validated onsubmit). The other option is for them to click No (radio button), I will not attend. If they choose this, then they should be able to submit without having to complete the form.

I have this code so far, and while I don't get an error on the page, the page does allow me to submit the form without filling out the mandatory fields when the radio button is checked. So something (lots probably) is missing. Help!

function check_radio ()
if (document.getElementById('radio1').checked == true)
{
function validate_form ()
{
if ( document.reg_form.vorname.value == "" ){
alert ( "Geben Sie bitte Ihren Vornamen ein" );
document.reg_form.vorname.focus();
document.reg_form.vorname.select();
return false;
}
if ( document.reg_form.nachname.value == "" ){
alert ( "Geben Sie bitte Ihren Nachnamen ein" );
document.reg_form.nachname.focus();
document.reg_form.nachname.select();
return false;
}
}
}
}
</script>

tomws
05-09-2008, 04:15 PM
This sticky thread (http://www.codingforums.com/showthread.php?t=82672) contains helpful information for posting messages in the forum. Specifically, the subject line is helpful. Good thing, though, is that your code is small. :)

If I'm seeing the structure correctly, I think you have part of it backwards. Should perhaps be something like:

function validate_form ()
{
if (document.getElementById('radio1').checked == true)
{
if ( document.reg_form.vorname.value == "" ){
alert ( "Geben Sie bitte Ihren Vornamen ein" );
document.reg_form.vorname.focus();
document.reg_form.vorname.select();
return false;
}
if ( document.reg_form.nachname.value == "" ){
alert ( "Geben Sie bitte Ihren Nachnamen ein" );
document.reg_form.nachname.focus();
document.reg_form.nachname.select();
return false;
}
}
else { /*not checked, validate something else*/ }
}

svennie12
05-09-2008, 04:37 PM
Yeah thanks, I know what you mean. If they don't check yes then they've checked 'no' and then we don't need to validate anything else. We basically want to say, if you check yes, then fill the mandatory fields and if you checked no you can go ahead and click submit and thats it. Does that make sense?

Hehe I'm about this close to bailing on this page because it's due today and not even IT can help me right now.

tomws
05-09-2008, 04:47 PM
We basically want to say, if you check yes, then fill the mandatory fields and if you checked no you can go ahead and click submit and thats it. Does that make sense?

Unless I misunderstand, then the modified code above will do that - after removing the else part anyway. And I suppose that your form tag would need to be something near <form ... onsubmit="validate_form();">