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
https://forums.phpfreaks.com/topic/224936-best-way-to-check-if-form-field-is-set/
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
}
}

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.

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.