sabinmash Posted October 28, 2011 Share Posted October 28, 2011 I recently followed a tutorial on PHP form validation, which should produce error messages on the same page after submition. It worked like a charm. Now I am trying it on my own and it doesn't seem to be working. (I apologize for any coding horrors your find below, I 'm a beginner.) Clicking submit without typing anything should produce an error that fields must be filled out. I only get that error if I click the gender radio buttons and submit. I am not sure where I went wrong here. Any advice would be very helpful to me. Thank you for your time. <?php //determine whether variables have already been declared by PHP, returns a boolean. if (isset($_POST['firstname'], $_POST['middleinitial'], $_POST['lastname'], $_POST['phone1'], $_POST['phone2'], $_POST['phone3'], $_POST['email'], $_POST['address'], $_POST['category'], $_POST['gender'])) { //array to hold error messages $errors = array(); $firstname = $_POST['firstname']; $middleinitial = $_POST['middleinitial']; $lastname = $_POST['lastname']; $phone1 = $_POST['phone1']; $phone2 = $_POST['phone2']; $phone3 = $_POST['phone3']; $email = $_POST['email']; $address = $_POST['address']; $category = $_POST['category']; $gender = $_POST['gender']; //make sure fields are not empty, if they are not empty, then break into //the else statement which contains the rest of the checks. if (empty($firstname) || empty($middleinitial) || empty($lastname) || empty($phone1) || empty($phone2) || empty($phone3) || empty($email) || empty($address) || empty($category)|| empty($gender)) { //append value to errors array (which we will do again and again) $errors[] = "All fields are required."; } else { //check age in a number and if it is, check that it's greater than 0. if (!is_numeric($phone1) || !is_numeric($phone2) || !is_numeric($phone3)) { $errors[] = "Telephone must be a number!"; } else { /*strpos — Find position of first occurrence of a string. strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) Searches haystack, for needle, and will returns the position as an integer. If needle is not found, strpos() will return boolean FALSE, which is how it's used here. */ if((strpos($phone1,".") !== false) || (strpos($phone2,".") !== false) || (strpos($phone3,".") !== false)){ $errors[] = 'Age must be a whole number!'; } } /*Statement below as a whole says " if email validation is false..." filter_var(Value to filter, The ID of the filter to apply.) Filters a variable with a specified filter*/ if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { $errors[] = 'Please enter a valid email address!'; } if (strlen($email) > 50) { $errors[] = "Email is too long!"; } } /*this if method allows to list all errors found from the array, by checking if there are any errors int he error array, if so, loop through each one of print it. If there are no errors, print msg.*/ if (!empty($errors)) { foreach ($errors as $error) { echo '<strong>', $error, '</strong><br />'; } } else { echo 'You\'ve been registered!'; } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/ Share on other sites More sharing options...
Psycho Posted October 28, 2011 Share Posted October 28, 2011 Your problem is the very first if statement and all the isset() conditions: if (isset($_POST['firstname'], $_POST['middleinitial'], $_POST['lastname'], $_POST['phone1'], $_POST['phone2'], $_POST['phone3'], $_POST['email'], $_POST['address'], $_POST['category'], $_POST['gender'])) For radio groups and checkboxes, the fields are only passed in the POST/GET data if an option is checked. Therefore if you have not selected a gender that first if() condition results in false and validation is never done. Besides you should NOT make that first if statement so elaborate. All you WANT to do is know if the form was submitted - do NOT check to see if ALL the fields were submitted. If anything, that would be part of the validation logic. You should simply use if($_SERVER['REQUEST_METHOD']=='POST') Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283042 Share on other sites More sharing options...
Psycho Posted October 28, 2011 Share Posted October 28, 2011 Hmm, you have some other problems in the logic and I'm working on a rewrite of your code. Per the current logic you are making the middle initial field required. Are you sure you want to do that? Many people have no middle name. Also, this makes no sense: if((strpos($phone1,".") !== false) || (strpos($phone2,".") !== false) || (strpos($phone3,".") !== false)) { $errors[] = 'Age must be a whole number!'; } What does a decimal in the phone numbers have to do with the age! Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283044 Share on other sites More sharing options...
sabinmash Posted October 28, 2011 Author Share Posted October 28, 2011 Sorry, the age part was leftover cut and pasted code from the tutorial. Thank you so much! The suggestion you made works well! I still would get an error afterwards saying: Php Notice: Undefined index: gender I suppressed it with : @$gender = $_POST['gender']; For now at least. You are right, some things do not have to be required, I suppose I was trying to be thorough. What other logic problems did you find? This is my first attempt at validation of any kind. Thank you again! Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283058 Share on other sites More sharing options...
Psycho Posted October 28, 2011 Share Posted October 28, 2011 You really need to sit back and figure out exactly how you want to validate certain data. Using an all inclusive methodology is not appropriate. For example, what do you consider a valid phone number? With your current logic it can ONLY consist of numeric digits. But, people are accustomed to entering phone numbers in formats such as 123-456-7890, 123.456.789, (13) 456-7890, or even 1-800-GET-BENT. So, you need to determine what makes sense for your application. For most purposes, I would simply check that the values contains 7 or 10 digits in the value and only store the digits. So, the value could contain other characters, but I would check that there are only 7 or 10 digits after stripping out the other characters. Also, create functions for any elaborate functions such as phone numbers - especially if you will need it more than once. Here is a quick rewrite of your original code. That's not to say this is production ready. I did not test it and I would probably make some other changes, but it should give you an idea of a more logical approach. function parsePhone($phone) { $phone = trim($phone); if($phone=='') { return $phone; } //Strip out non numbers $phone = preg_replace("#[^\d]#", '', $phone); if (strlen($phone)!=7 && strlen($phone)!=10) { return false; } else { return $phone; } } //determine if the form was submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { //array to hold error messages $errors = array(); //Process post value $firstname = isset($_POST['firstname']) ? trim($_POST['firstname'] : false; $middleinitial = isset($_POST['middleinitial']) ? trim($_POST['middleinitial']) : false; $lastname = isset($_POST['lastname']) ? trim($_POST['lastname']) : false; $phone1 = isset($_POST['phone1']) ? trim($_POST['phone1']) : false; $phone2 = isset($_POST['phone2']) ? trim($_POST['phone2']) : false; $phone3 = isset($_POST['phone3']) ? trim($_POST['phone3']) : false; $email = isset($_POST['email']) ? trim($_POST['email']) : false; $address = isset($_POST['address']) ? trim($_POST['address']) : false; $category = isset($_POST['category']) ? trim($_POST['category']) : false; $gender = isset($_POST['gender']) ? trim($_POST['gender']) : false; //Only accept numbers for phone numbers //Do a validation of required fields if (!$firstname || !$lastname || !$phone1 || !$email || !$address || !$category || !$gender) { //append value to errors array (which we will do again and again) $errors[] = "All required fields have not been entered."; } else { //Check that phone numbers (if entered) are 7 or 10 digits? Don't know what your needs are. $phone1 = validPhone($phone1); $phone2 = validPhone($phone2); $phone3 = validPhone($phone3); if ($phone1===false) { $errors[] = "Telephone #1 is not valid"; } if ($phone2===false) { $errors[] = "Telephone #2 is not valid"; } if ($phone3===false) { $errors[] = "Telephone #3 is not valid"; } /*Statement below as a whole says " if email validation is false..." filter_var(Value to filter, The ID of the filter to apply.) Filters a variable with a specified filter*/ if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { $errors[] = 'Please enter a valid email address!'; } elseif (strlen($email) > 50) { //Make this an elseif - don't need to validate length if the format is not valid $errors[] = "Email is too long!"; } } /*this if method allows to list all errors found from the array, by checking if there are any errors int he error array, if so, loop through each one of print it. If there are no errors, print msg.*/ if (!empty($errors)) { foreach ($errors as $error) { echo '<strong>', $error, '</strong><br />'; } } else { echo 'You\'ve been registered!'; } } Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283085 Share on other sites More sharing options...
sabinmash Posted October 28, 2011 Author Share Posted October 28, 2011 The application directions I am attempting to follow says PHP or JS should verify the non-numeric entries. I interpreted that as blocking any non-numeric character, maybe I was wrong. The code you wrote is teaching me a lot, thank you very much! I am a little confused about some things. I see the function you wrote that takes out non-numerics, and returns false if not 7 or 10 digits. I am wondering how this is meant to be implimented? I have used it as such: $phone = "$phone1"."$phone2"."$phone3"; parsePhone($phone); echo $phone; The phone number sections get combined into one number, then parse for non numeric values and length using the parsePhone() function, and echoed to check it. However, when I type in a phone number with letters, the letters are printed too, I thought it was stripping them? I think my problem is not knowing exactly how this works: $phone = preg_replace("#[^\d]#", '', $phone); Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283122 Share on other sites More sharing options...
Psycho Posted October 28, 2011 Share Posted October 28, 2011 The application directions I am attempting to follow says PHP or JS should verify the non-numeric entries. I interpreted that as blocking any non-numeric character, maybe I was wrong. If you wish you can certainly reject values that are not completely numeric. But, that is not very user friendly. But, that is a decision YOU need to make based upon your needs and requirements. I am a little confused about some things. I see the function you wrote that takes out non-numerics, and returns false if not 7 or 10 digits. I am wondering how this is meant to be implimented? I have used it as such: $phone = "$phone1"."$phone2"."$phone3"; parsePhone($phone); echo $phone; The phone number sections get combined into one number, then parse for non numeric values and length using the parsePhone() function, and echoed to check it. However, when I type in a phone number with letters, the letters are printed too, I thought it was stripping them? I think my problem is not knowing exactly how this works: $phone = preg_replace("#[^\d]#", '', $phone); Not sure what you are doing there. I see no logical reason to try to validate three different phone numbers as a concatenated value. I made some assumptions in the changes I made. For example I made the first phone number required, but not the other three. Again, from a user stand-point that just doesn't make sense. Many people do not have three phone numbers. The function simply strips out all non-numeric digits then tests if there are 7 or 10 digits. If no, then false is returned (i.e. not a valid phone number). However, if the value did contain just 7 or 10 digits then a string of just the numeric digits is returned. This line $phone = preg_replace("#[^\d]#", '', $phone); is what strips out the non-numeric digits. The \d represents numeric characters and the ^ means (is not). So, the function replaces any characters that are not digits with an empty character and then returns the result. Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283127 Share on other sites More sharing options...
sabinmash Posted October 28, 2011 Author Share Posted October 28, 2011 Oh I'm so sorry, I think we have some confusion about the phone fields. That s all for 1 phone number, the first field is the area code, and the next 2 complete the phone number. So phone1: area code (like 249), phone2: 555, phone3: 6666. Concatenated together as 2495556666, a normal US 10 digit number. It's like this because it's what it required for the application. It will be stored int he database as one complete number like this. This is why i parce $phone (which holds all the numbers together), rather than phone1, because that would just be one section of a complete number. Knowing this, how is the phone function intended to work? Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283138 Share on other sites More sharing options...
Psycho Posted October 28, 2011 Share Posted October 28, 2011 Knowing this, how is the phone function intended to work? I thought I already explained that. It takes the input, strips out all non-numeric characters and then tests if the result is 7 or 10 characters. If not, it returns false, if yes it returns the stripped value (i.e. the numeric digits.). You state It's like this [three fields for one phone number] because it's what it required for the application. It will be stored int he database as one complete number like this. If the value is stored as a single value then how is it a "requirement" to be three fields? Not that I care. I see many application that require the user to enter the three parts separately. I just think it is lazy since it is not difficult to allow the user to enter the data into a single field and validate it appropriately. Personally, I hate that type of UI. It is so much easier to enter a single field and enter my phone number rather than entering three digits, press tab, enter another three digits, press tab, then enter the last four. But, that is just my opinion. So, based on your needs, you could concatenate the value before calling the function and remove the check for 7 digits. Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283143 Share on other sites More sharing options...
sabinmash Posted October 28, 2011 Author Share Posted October 28, 2011 Sorry, I didn't mean to ask the same thing twice. I meant to ask why does the phone string still have non numerics in it when I echo it? <?php function parsePhone($phone) { $phone = trim($phone); if($phone=='') { return $phone; } //Strip out non numbers $phone = preg_replace("#[^\d]#", '', $phone); if (strlen($phone)!=10) { $errors[] = "You must enter a 10 digit phone number."; return false; } else { return $phone; } } //determine if the form was submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { //array to hold error messages $errors = array(); //Process post value $firstname = isset($_POST['firstname']) ? trim($_POST['firstname']) : false; $middleinitial = isset($_POST['middleinitial']) ? trim($_POST['middleinitial']) : false; $lastname = isset($_POST['lastname']) ? trim($_POST['lastname']) : false; $phone1 = isset($_POST['phone1']) ? trim($_POST['phone1']) : false; $phone2 = isset($_POST['phone2']) ? trim($_POST['phone2']) : false; $phone3 = isset($_POST['phone3']) ? trim($_POST['phone3']) : false; $email = isset($_POST['email']) ? trim($_POST['email']) : false; $street = isset($_POST['street']) ? trim($_POST['street']) : false; $city = isset($_POST['city']) ? trim($_POST['city']) : false; $state = isset($_POST['state']) ? trim($_POST['state']) : false; $category = isset($_POST['category']) ? trim($_POST['category']) : false; $gender = isset($_POST['gender']) ? trim($_POST['gender']) : false; //Do a validation of required fields if (!$firstname || !$lastname || !$phone1 || !$email || !$street|| !$city|| !$state || !$category || !$gender) { //append value to errors array (which we will do again and again) $errors[] = "All required fields have not been entered."; } else { $phone = "$phone1"."$phone2"."$phone3"; parsePhone($phone); echo $phone; /*Statement below as a whole says " if email validation is false..." filter_var(Value to filter, The ID of the filter to apply.) Filters a variable with a specified filter*/ if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { $errors[] = 'Please enter a valid email address!'; } elseif (strlen($email) > 50) { //Make this an elseif - don't need to validate length if the format is not valid $errors[] = "Email is too long!"; } } /*this if method allows to list all errors found from the array, by checking if there are any errors int he error array, if so, loop through each one of print it. If there are no errors, print msg.*/ if (!empty($errors)) { foreach ($errors as $error) { echo '<strong>', $error, '</strong><br />'; } } else { echo 'You\'ve been registered!'; } } ?> If for the 3 phone fields I have 333 444 555k, the concatenated phone number still outputs 333444555k. Shouldn't the k not be there anymore? Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283156 Share on other sites More sharing options...
Psycho Posted October 28, 2011 Share Posted October 28, 2011 You aren't using the function as intended. But, that is partially my fault. When I created the function I initially intended it to be used to simply "parse" the phone number, but halfway through I decided a different approach was better. The function should really be called validPhone(). As I stated earlier, if the function finds that the phone is not valid it returns false - otherwise it returns the numeric string. You used the function like this parsePhone($phone); That doesn't do anything to the variable $phone - you would need to assign the return value of the function to a variable $phone = parsePhone($phone); Now, $phone will be false if the passed value cannot be parsed into a valid 10 digit number, else it returns the 10 character string of numeric digits. Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283168 Share on other sites More sharing options...
sabinmash Posted October 31, 2011 Author Share Posted October 31, 2011 I realized the following code does not put anything into the variables: //Process post value $firstname = isset($_POST['firstname']) ? trim($_POST['firstname']) : false; $middleinitial = isset($_POST['middleinitial']) ? trim($_POST['middleinitial']) : false; $lastname = isset($_POST['lastname']) ? trim($_POST['lastname']) : false; $phone1 = isset($_POST['phone1']) ? trim($_POST['phone1']) : false; $phone2 = isset($_POST['phone2']) ? trim($_POST['phone2']) : false; $phone3 = isset($_POST['phone3']) ? trim($_POST['phone3']) : false; I'm not entirely sure what these lines are supposed to do. I understand isset() and trime(), but how about the "?" and ":false" ? I'm not sure how it fits all together into one line, and I'm not sure if these lines are doing what they are meant to be doing since nothing seems to be put into the varaible when I set them to session variables. Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283575 Share on other sites More sharing options...
Pikachu2000 Posted October 31, 2011 Share Posted October 31, 2011 That's ternary syntax, which is essentially a shorthand if/else conditional. See example #2 here: http://us3.php.net/manual/en/language.operators.comparison.php Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283582 Share on other sites More sharing options...
sabinmash Posted October 31, 2011 Author Share Posted October 31, 2011 This worked perfectly until a huge power outage hit, this is the most recent file I have, it looks like the most recent one, but the validation doesnt work and it goes straight to the confirmation page no matter what. I checked it many times, and I cant figure it out. I think it has to do with the action tag if statements. Sorry for the huge block of code. Does anything pop out as wrong? <?php $link_register = 1; include("header.php"); function parsePhone($phone) { $phone = trim($phone); if($phone=='') { return $phone; } //Strip out non numbers $phone = preg_replace("#[^\d]#", '', $phone); if (strlen($phone)!=10) { return false; } else { return $phone; } } //determine if the form was submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { //array to hold error messages $errors = array(); //Process post value $firstname = isset($_POST['firstname']) ? trim($_POST['firstname']) : false; $middleinitial = isset($_POST['middleinitial']) ? trim($_POST['middleinitial']) : false; $lastname = isset($_POST['lastname']) ? trim($_POST['lastname']) : false; $phone1 = isset($_POST['phone1']) ? trim($_POST['phone1']) : false; $phone2 = isset($_POST['phone2']) ? trim($_POST['phone2']) : false; $phone3 = isset($_POST['phone3']) ? trim($_POST['phone3']) : false; $email = isset($_POST['email']) ? trim($_POST['email']) : false; $street = isset($_POST['street']) ? trim($_POST['street']) : false; $city = isset($_POST['city']) ? trim($_POST['city']) : false; $state = isset($_POST['state']) ? trim($_POST['state']) : false; $category = isset($_POST['category']) ? trim($_POST['category']) : false; $gender = isset($_POST['gender']) ? trim($_POST['gender']) : false; //Do a validation of required fields if (!$firstname || !$lastname || !$phone1 || !$phone2 || !$phone3 || !$email || !$street|| !$city|| !$state || !$category || !$gender) { //append value to errors array (which we will do again and again) $errors[] = "All required fields have not been entered."; } else { $phone = "$phone1"."$phone2"."$phone3"; $phone = parsePhone($phone); if ($phone === false){ $errors[] = "You must enter a 10 digit phone number."; } /*Statement below as a whole says " if email validation is false..." filter_var(Value to filter, The ID of the filter to apply.) Filters a variable with a specified filter*/ if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { $errors[] = 'Please enter a valid email address!'; } } } ?> <div id="banner-wrap"> <div id="banner" class="container_24 rounded"> <h2> Sign up for Drawing Club</h2> <?php /*this if method allows to list all errors found from the array, by checking if there are any errors int he error array, if so, loop through each one of print it. If there are no errors, print msg.*/ if (!empty($errors)) { foreach ($errors as $error) { echo '<strong>', $error, '</strong><br /><br />'; } } ?> <form action=" <?php if(empty($errors)){ echo "confirmation.php"; } else { echo "register.php"; } ?>" method="POST"> <table> <tr> <td>Name: </td> <td><input type="text" name="firstname" value="warren" id="search" placeholder="First name" class="rounded" maxlength="30"/></td> <td><input type="text" name="middleinitial" value="f" id="search" placeholder="Middle Inital" class="rounded" maxlength="1"/></td> <td><input type="text" name="lastname" value="grant" id="search" placeholder="Last name" class="rounded" maxlength="30"/></td> </tr> <tr> <td>Telephone: </td> <td><input type="text" name="phone1" value="555" id="search" placeholder="Telephone" class="rounded" size="3" maxlength="3"/>-</td> <td><input type="text" name="phone2" value="666" id="search" placeholder="Telephone" class="rounded" size="3" maxlength="3"/>-</td> <td><input type="text" name="phone3" value="8888" id="search" placeholder="Telephone" class="rounded" size="4" maxlength="4"/></td> </tr> <tr> <td>Email: </td> <td><input type="text" name="email" value="whard@great.com" id="search" placeholder="Email" class="rounded" size="20" maxlength="50"/></td> </tr> <tr> <td>Address: </td> <td><input type="text" name="street" value="22 Grassy Lane" id="search" placeholder="Street" class="rounded" /></td> <td><input type="text" name="city" value="Woodsy" id="search" placeholder="City" class="rounded" /></td> <td><input type="text" name="state" value="NY" id="search" placeholder="State" class="rounded" /></td> </tr> <tr> <td class="category">Category</td> <td align="left"> <select multiple class="rounded" name="category[]" size="2"> <option value="livemodel">Live Model</option> <option value="museum">Museum</option> <option value="subwaysketch">Subway Sketch</option> <option value="digital">Digital</option> </select> </td> </tr> <tr> <td>Gender: </td> <td><input id="radio" class="rounded" type="radio" name="gender" value="male" /> Male</td> <td><input id="radio" class="rounded" type="radio" name="gender" value="female" /> Female</td> </tr> </table> <button type="submit" value="Register" /> REGISTER </button> </form> </div> <p id="breadcrumbs" class="container_24 rounded"> You're here: <a href="#">Home</a> > <a href="#">Welcome</a> </p> </div> <!-- end banner-wrap --> <?php include("footer.php"); ?> Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283594 Share on other sites More sharing options...
sabinmash Posted October 31, 2011 Author Share Posted October 31, 2011 Oh, also the short variables dont seem to be getting anything put into them. That's the only other clue i have Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283595 Share on other sites More sharing options...
PFMaBiSmAd Posted October 31, 2011 Share Posted October 31, 2011 So, the conditional action="" form code (question in a different thread in the forum) got added to this code. When the page is first requested, there are no errors and the logic that determines the action= says to use the confirmation.php page. Until you get your form and the form validation code finished and working the way you want, don't do anything like that yet. Just use an empty action="" attribute to get the form to submit to the same page. As to the validation code - 1) You should be developing and debugging php code with error_reporting set to E_ALL and display_errors set to ON in your master php.ini so that php will help you by reporting and displaying all the errors it detects. You would be getting an error at the trim() statement for the $_POST['category'] because an array is being submitted. Since it is an array, which no one here knew prior to your reply above, it needs different handling and you wouldn't use trim on it directly. 2) You should not lump together all the tests for 'empty' fields (the current code actually doesn't test for empty values) and output one generic error message. You should individually validate each field and output a unique error message telling the visitor exactly what is wrong with each value (i.e. LastName is empty, No category chosen, ...) This will both help make the final produce better and it will tell you where your current problem is. Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283602 Share on other sites More sharing options...
PFMaBiSmAd Posted October 31, 2011 Share Posted October 31, 2011 I recommend starting with the following code (please read the comments in it because this is not complete code) - <?php $link_register = 1; // I'll assume you use this variable? include("header.php"); function parsePhone($phone) { $phone = trim($phone); if($phone=='') { return $phone; } //Strip out non numbers $phone = preg_replace("#[^\d]#", '', $phone); if (strlen($phone)!=10) { return false; } else { return $phone; } } function trim_deep(&$item){ // used by array_walk_recursive to trim all elements of an array, w/sub arrays,... $item = trim($item); } //determine if the form was submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { //array to hold error messages $errors = array(); array_walk_recursive($_POST, 'trim_deep'); // trim all elements of the $_POST array (the result is put back into the $_POST array) // required text fields - firstname, lastname, phone1, phone2, phone3, email, street, city, state // optional text fields - middleinitial // The array keys are the form field name, the array values are the legend/name to display in the error message. $required = array('firstname'=>'First Name', 'lastname'=>'Last Name', 'phone1'=>'Area Code', 'phone2'=>'Phone Number', 'phone3'=>'Phone Number', 'email'=>'Email', 'street'=>'Street Address', 'city'=>'City', 'state'=>'State'); foreach($required as $key=>$value){ if($_POST[$key] ==''){ $errors[] = "$value is empty!"; } // do any other common filtering/validation on the required fields here... } // do any filtering/validation on the optional text fields here... // if middleinitial is present, filter it as needed // do any validation of the category (array) field here (in case someone didn't use the form to submit it) // if at least one category choice is required, perform that check here... // do any validation of the gender field here (in case someone didn't select one or didn't use the form to submit it) // check if one of the other radio choice was picked... // do specific filtering/validation of the phone number here... if(!empty($_POST['phone1']) && !empty($_POST['phone2']) && !empty($_POST['phone3'])){ // only if all three parts are not empty $phone = parsePhone($_POST['phone1'].$_POST['phone2'].$_POST['phone3']); if ($phone === false){ $errors[] = "You must enter a 10 digit phone number."; } } // do specific filtering/validation of the email here... if(!empty($_POST['email'])){ // only if not empty /*Statement below as a whole says " if email validation is false..." filter_var(Value to filter, The ID of the filter to apply.) Filters a variable with a specified filter*/ if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === FALSE) { $errors[] = 'Please enter a valid email address!'; } } // other filtering/validation tests here... // all filtering/validation done at this point. // if there are no errors, use the data. if(empty($errors)){ // do something with the submitted data here... echo "The form data was successfully submitted"; } } // end of the form processing code ?> ... the remainder of your code on the page ... Quote Link to comment https://forums.phpfreaks.com/topic/249994-form-validation-not-producing-the-error-messages-when-it-should/#findComment-1283609 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.