Jump to content

Best Way To Check If Form Field Is Set?


phprocker

Recommended Posts

Hey all. What is the best way to check if a form field has been entered by the user? Because a field left blank by the user still shows up as set with the isset function.

 

Example:

if (isset($_POST['name']))
{
echo "The field is set";
}

 

This is a problem if I'm checking if the user has skipped over the name field on a form because an empty value gets passed to the POST array even if the field is left blank.

 

Do people use empty or a regular expression instead?

 

Cheers!

Link to comment
Share on other sites

Since it's reasonable to assume that a name should have at least one character:

if( isset($_POST['name']) ) {
$name = trim($_POST['name']);
if( strlen($name < 1 ) ) {
	// name is invalid, error condition exists
} else {
	// name has at least one character
}
}

Link to comment
Share on other sites

You can also do:

 

if(!empty($_POST['name']) && isset($_POST['name']))

{

    echo 'Field is not empty and is set';

}

else

{

  echo 'Your field is empty';

}

 

You can just check whether the string is blank and use isset. It's good practice to use isset because of undefined index errors.

 

Unfortunately, both of those will allow a space in a field, by itself to pass as valid input.

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.