phprocker Posted January 19, 2011 Share Posted January 19, 2011 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! Quote Link to comment Share on other sites More sharing options...
DarkRanger Posted January 19, 2011 Share Posted January 19, 2011 I use if ( $_POST['name']=="" || $_POST['name']==NULL ) { echo "The field is NOT set"; } perhaps this is what you want?? Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted January 19, 2011 Share Posted January 19, 2011 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 } } Quote Link to comment Share on other sites More sharing options...
coupe-r Posted January 19, 2011 Share Posted January 19, 2011 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'; } Quote Link to comment Share on other sites More sharing options...
Porl123 Posted January 19, 2011 Share Posted January 19, 2011 You can just check whether the string is blank and use isset. It's good practice to use isset because of undefined index errors. Quote Link to comment Share on other sites More sharing options...
phprocker Posted January 19, 2011 Author Share Posted January 19, 2011 Thanks for the great input guys. All clear now. Cheers! Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted January 19, 2011 Share Posted January 19, 2011 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.