Jump to content

How to check when a form field is left blank


SaranacLake

Recommended Posts

I have a form with a gender control made up of two radio buttons.

If the user doesn't fill out this form, nothing gets submitted (i.e name='gender') in the $_POST array.

So how ae you supposed to verify that the form field was left blank, and use that information to say display an error message on the form?

Edited by SaranacLake
Link to comment
Share on other sites

I am reading through some old code which generates a dynamic survey and trying to get my head into things.

My old code - which is too complicated to post here - doesn't check if something like "gender" gets left blank, and I;d like to fix that.

So I was looking at another script that is much simpler, but now it seems that I don't understand that one either?!

Here is a snippet from my simpler script - which definitely works - but which isn't helping me figure out my more complicated script...

	<?php
	    if ($_SERVER['REQUEST_METHOD']=='POST'
        var_dump($_POST);
        exit();
        
        
        $trimmed = array_map('trim', $_POST);
        
        if (!isset($trimmed['gender'])){
            $gender = 0;
            
        }else{
            if (($trimmed['gendr'] == 1 || $trimmed['gender'] == 2)){
                $gender = $trimmed['gender'];
                
            }else{
                $errors['gender'] = "Gender must be 'Male' or 'Female'.";
            }
        }
        
        //and so on...
?>
	
<input id="gender_opt1" type="radio" name="gender" value="1" <?php echo (isset($gender) && gender == "1") ? 'checked="checked"' : ''; ?> />
	<input id="gender_opt2" type="radio" name="gender" value="2" <?php echo (isset($gender) && gender == "2") ? 'checked="checked"' : ''; ?> />
 
	

 

Haven't been outside in 3 days due to horrible weather, and my brain is fried, so maybe you all can help me see something obvious that I can't seem to see?!  :confused:

 

Link to comment
Share on other sites

1 hour ago, SaranacLake said:

So how ae you supposed to verify that the form field was left blank, and use that information to say display an error message on the form?

You already know the answer:

1 hour ago, SaranacLake said:

If the user doesn't fill out this form, nothing gets submitted (i.e name='gender') in the $_POST array.

Link to comment
Share on other sites

The snippet you posted is missing a closing parenthesis. Assuming that somehow didn't throw an error, the lack of curly braces means that the var_dump() is only run if the request method is $_POST, but the exit() is always run.

Edited by maxxd
Link to comment
Share on other sites

5 minutes ago, maxxd said:

The snippet you posted is missing a closing parenthesis. Assuming that somehow didn't throw an error, the lack of curly braces means that the var_dump() is only run if the request method is $_POST, but the exit() is always run.

I just manually retyped in my code from another computer.

Yeah, I had a few type-o's, but that's not the issue.

 

Link to comment
Share on other sites

1 hour ago, requinix said:

You already know the answer:

..

1 hour ago, requinix said:

You already know the answer:

I think this addresses the issue with my simpler script...

	<?php
	    if ($_SERVER['REQUEST_METHOD']=='POST'){
//        var_dump($_POST);
//        exit();
        
        
        $trimmed = array_map('trim', $_POST);
        
        if (!isset($trimmed['gender'])){
//            $gender = 0;
            $errors['gender'] = "Please choose a gender";        // NEW
            
        }else{
            if (($trimmed['gender'] == 1 || $trimmed['gender'] == 2)){
                $gender = $trimmed['gender'];
                
            }else{
                $errors['gender'] = "Gender must be 'Male' or 'Female'.";
            }
        }
        
        //and so on...
    }
?>
	
<input id="gender_opt1" type="radio" name="gender" value="1" <?php echo (isset($gender) && gender == "1") ? 'checked="checked"' : ''; ?> />
	<input id="gender_opt2" type="radio" name="gender" value="2" <?php echo (isset($gender) && gender == "2") ? 'checked="checked"' : ''; ?> />
 
	

 

And, yeah, I guess I did have the answer, but it threw me off not seeing anything in the $_POST array.

I guess PHP is smart enough to respond in the negative if I ask for a component of the $_POST array that isn't there (e.g. $trimmed['gender'])

 

 

Link to comment
Share on other sites

I can't make this work for my more complex script which has a multi-dimensional array...

On a side note, if you had a survey on your website about an article, would it be necessary to require the user to complete all questions, or is that undesirable?

(That is why I am struggling with this old code - I wanted to add error messages for any fields left unanswered.  But maybe I don't want to do that even if I can figure it out technically?)  :confused;

Link to comment
Share on other sites

20 minutes ago, SaranacLake said:

I can't make this work for my more complex script which has a multi-dimensional array...

Of course not: you try to trim() every value in $_POST, and that's not going to work for values that are themselves arrays. You'll have to find an alternative to array_map + trim...

 

20 minutes ago, SaranacLake said:

On a side note, if you had a survey on your website about an article, would it be necessary to require the user to complete all questions, or is that undesirable?

It's impolite to require people to answer every question - especially personal questions. But there may be times when specific questions need an answer for the survey to be useful. Use your best judgment.

 

20 minutes ago, SaranacLake said:

(That is why I am struggling with this old code - I wanted to add error messages for any fields left unanswered.  But maybe I don't want to do that even if I can figure it out technically?)  :confused;

Yeah, confused.

If an answer is required then give an error if they didn't give an answer. If it is not required then don't give an error.

Link to comment
Share on other sites

1 minute ago, requinix said:

Of course not: you try to trim() every value in $_POST, and that's not going to work for values that are themselves arrays. You'll have to find an alternative to array_map + trim...

Well, the snippet above doesn't reflect my more complex script, so that doesn't apply.

 

1 minute ago, requinix said:

It's impolite to require people to answer every question - especially personal questions. But there may be times when specific questions need an answer for the survey to be useful. Use your best judgment.

Yeah, but the article survey is voluntary...

IF someone decides to complete it, then I sorta expect they answer all of the Yes/No and multiple choice questions - although not necessarily the open-ended ones.

 

1 minute ago, requinix said:

Yeah, confused.

If an answer is required then give an error if they didn't give an answer. If it is not required then don't give an error.

Let me try to explain what I have, because there is n way to post thousands of lines of code and include a large database.

My scripts create surveys based on a survey map which defines the questions, plus linked tables that build things like multiple choices.

Everything runs great except I never really figured a way to do data validation on my more complex survey.

If a question in the survey map is Yes-No, then I had this snippet...

(Hint: This is a snippet, and the syntax isn't the issue, so pardon brevity or type-o's.)

This script builds each survey item...

	case 'YN':
    $item = "<li>
                blah blah
                <input id='question_$questionID" . "_Y' name='questionResponse[$questionID]' type='radio' value='1' " 
                . ((isset($responseArray[$question]) && $reviewArray[$questionID] == '1') ? "checked='checked'" : "") . " />"
            
                and so on...
	

 

Then I have my calling script which which is similar to my earlier posts.

However, in the simpler "gender" example, that is doable because all form values are hard-coded, so I can say...

	        if (!isset($trimmed['gender'])){
//            $gender = 0;
            $errors['gender'] = "Please choose a gender";        // NEW
	

 

 

What makes my current problem so tricky is that things aren't hard-coded, they are dynamic.

And if I submit the form with not entries, the only thing that shows up in the $_POST array are text boxes as ' '.

So I can't check if they answered "Q1.) Did you like this article? (Y/N)?" because it never registers in the $_POST array?!

 

With my original code - snippet above - I am getting a $_POST array like this if I complete answers...

	array
    'questionResponse' =>
        array
            1 => 1
            2 => I liked this article because it was detailed...
            3 => 1
            4 => I learned how to....
	

 

I thought that adding a [yn] "hook" like this might help...

	    $item = "<li>
                blah blah
                <input id='question_$questionID" . "_Y' name='questionResponse[$questionID][yn]' type='radio' value='1' " 
                . ((isset($responseArray[$question]) && $reviewArray[$questionID] == '1') ? "checked='checked'" : "") . " />"
            
                and so on...
	

 

and in the calling script this...

	            foreach($_POST['questionResonse'] as $questionID => $surveyResponse){
                if (!isset($surveyResponse['yn'])){
                    set some error message...
                }
            }
	

 

I think this would be a great place to use Javascript to do data validation on the front-end, but that isn't a solution for now.

Besides, I would like to see how to do this using PHP.

if I can't get this working, my script does work otherwise, and I do have a PHP check to not allow submittal of a completely blank survey, but I would prefer people answer all of the TF, YN, multiple-chocie questions as there are only like 4-5 of them.  They can skip the open-ended questions fi they like.)

 

Is it possible to make this work using PHP?

 

Link to comment
Share on other sites

Make an array of the required form fields in php, then loop through that array on submission. If any of the fields are empty, add a message to an errors array. In the end of the actual, full form processing script if the errors array isn't empty, loop through the errors array and print out each individual error.

  • Like 1
Link to comment
Share on other sites

11 hours ago, maxxd said:

Make an array of the required form fields in php, then loop through that array on submission. If any of the fields are empty, add a message to an errors array. In the end of the actual, full form processing script if the errors array isn't empty, loop through the errors array and print out each individual error.

I am trying to use your advice above to address this issue.

(Now that I got my query and fetch working in my other thread, hopefully I can figure out how and where to use this advice to fix things.

(These scripts that I am working on now were written 6 1/2 years ago, are very intense, and use LOTS of arrays - which I still hate to this day - so it's a real bear to del with.  But the purpose of my code review is to get my head back into things, and try to fix/improve things that should be addressed.  if I can just get this and a similar script fixed, then I am in the home-stretch to completing reviewing my entire website, although I still have to cod ethe e-commerce module, but the end is in sight!)

Link to comment
Share on other sites

17 hours ago, maxxd said:

Make an array of the required form fields in php, then loop through that array on submission. If any of the fields are empty, add a message to an errors array. In the end of the actual, full form processing script if the errors array isn't empty, loop through the errors array and print out each individual error.

@maxxd

I was able to take your advice and write a block of code to do what you suggested last night.

have gotten error message starting to appear for some question types, but now I need to figure out how to logically incorroate this new code into my old code base which is going to be a bear - but I am getting there!

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.