Jump to content

php form, only require if another field is filled..


joetaylor

Recommended Posts

ok, after hours trying to figure this out myself, I thought it was about time I joined a php community anyway. :)

 

I built a html web form.  It uses a php script to check for required fields and send the e-mail if it passes.  Just checking for a single field is filled, or not, is pretty straightforward and works like this..

  if(empty($dob)) {
    $error_message .= 'Error: dob required';
  }
  if(empty($dayphone)) {
    $error_message .= 'Error: day phone required';
  }

But I have a couple situations in the form where I need to only require another field if another field (or radio) is filled.

 

There's a field for Mobile Phone.  Under that I have two radio buttons that answer Allow Texts?  yes/no

<label for="mobphone"> Mobile Phone: </label> <input type="text" name="mobphone" id="fields"><br> 
				</div>
                <div id="form-radio">
                <label for="texts"> Allow Texts? </label>
                	<input type="radio" name="texts" value="yes">Yes
			<input type="radio" name="texts" value="no">No
		</div>

This was my best try...

   if(isset($mobphone) && empty($texts)) {
    $error_message .= 'Error: Allow Texts yes or no required';
  }

... and now, you probably know my level of php experience.   :blink:  ..I'm learning. lol

 

Am I on the right track?  Is it possible to do this?  a Better way?

 

The other fields with the same scenario are similar,.. they aren't radio buttons.  They are drop down or text fields.

 

Thanks for any help in advance!

 

~Joe

 

 

This was my best try...

   if(isset($mobphone) && empty($texts)) {
    $error_message .= 'Error: Allow Texts yes or no required';
  }

 

Well, I assume you are SETTING $mobphone using something like

 

$mobphone = $_POST['mobphone'];

 

So, it would always be set. You should check that it has a value. You can use empty(), but that has some downsides. For example a value of '0' will be considered empty. But, using the same logic as you have now, you could do this

 

if(!empty($mobphone) && empty($texts))
{
    $error_message .= 'Error: Allow Texts yes or no required';
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.