PHP - Simple Form Validation
I'm having trouble with this form. I can't seem to figure out the rest of what is required I have already done most of it...I'm just stuck on these parts:
Province Select : (AutoGeneration, Multiple Select, Memory) AutoGeneration using Provinces Array: The Province Select box is generated by PHP using this array: provinces.txt Cut and paste this array into your own code. Multiple Selections: Note that the province select box permits multiple values to be selected. View the HTML source to see the configuration details. Also note how $_POST delivers these multiple values as an array. Select Box Memory: The Province select box retains the user choices after a POST. For each province selected by the user, your code will generate the "selected" attribute in the <options> tag for that province. View the HTML source of the working solution to see how this works. Status CheckBoxes (Multiple Select, Memory) Multiple Selections: Note that these checkboxes have been configured in the HTML to permit multiple selections. Also note that $_POST delivers these multiple selection values in an array. Status Box Memory:The Status Box retains the user choices after a POST. Your code will need to generate the "checked" attribute in the <input> tag for each item selected. Do not generate the checkboxes with an array. Location Radio button: Do not generate the radio buttons with an array. The Location radio button retains the user choice after a POST. Validation Success Message: Where does it go - The final success message is placed within the <div class="success"></div> tags at the top of the HTML. Use a Loop: Generate the success message with a single array loop that reads the $_POST array and prints out the success message as an ordered list. Form Variables List Un-Ordered List - The form variables are displayed in an unordered list . CSS removes the bullet. Names Capitolised - The names of the form variables are capitolised ( use strtoupper() function ) . Handle Empty Values - Print "---None supplied---" if the variable is empty. Province Long Names - Print the long names of the provinces selected as comma separated string Status Choices - Print the status choices as a comma separated string. Functions I need to use: empty() - is the string empty. Unfortunately, a "0" value counts as an empty string. strlen() - returns the number of characters in a string. is_numeric() - is the string a number count() - how many rows in an array is_array() - is the variable an array isset() - does the variable or member of array exist in_array() -does this string exist in this array strtoupper() - convert string to upper case. join() - you'll want this one too. Converts an array of strings into a string with a delimiter. error_reporting(E_ALL ^ (E_NOTICE | E_WARNING)); - suppresses warning messages in your code. Place at top. foreach ($_POST as $KEY => $VAL) {} - walk through the $_POST array (or any array) My code: Code: [Select] <!--"StAuth10065: I Adam Graham, 000136921 certify that this material is my original work. No other person's work has been used without due acknowledgement. I have not made my work available to anyone else."--> <? $PROVINCES = array( "--" => "--- Please Select Provinces ---", "nf"=>"Newfoundland", "pe"=>"Prince Edward Island", "nb"=>"New Brunswick", "ns"=>"Nova Scotia", "qc"=>"Quebec", "on"=>"Ontario", "mb"=>"Manitoba", "sk"=>"Saskatchewan", "ab"=>"Alberta", "bc"=>"British Columbia", "nt"=>"Northwest Territories"); if ($_SERVER['REQUEST_METHOD'] == 'GET') { $dimwelcomeMsg = TRUE; } if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_POST['uname'] == ''){ $errMsgs['uname'] = "Username must not be blank!!!"; $unameInError = true; } if (empty($_POST['year']) == TRUE){ $errMsgs['year'] = "Year must not be blank!!"; } if (count($errMsg) > 0 ): $dispErrorMsg = TRUE; else: foreach ($_POST as $key => $val): $key = strtoupper($key); $successMsg[$key] = $val; endforeach; $dispSuccessMsg = TRUE; endif; } ?> <html > <head> <title>Comp10065 - Simple Form Validatioon</title> <style type="text/css"> body { margin: 0; padding: 0; font: 80%/1.5 Arial,Helvetica,sans-serif; color: #111; background-color: green; } h2 { margin: 0px; padding: 10px; font-family: Georgia, "Times New Roman", Times, serif; font-size: 200%; font-weight: normal; color: #FFF; background-color: #CCC; border-bottom: #BBB 2px solid; } h1 {color:#006600} p#copyright { margin: 20px 10px; font-size: 90%; color: #999; } div.form-container { margin: 10px; padding: 5px; background-color: #FFF; border: #EEE 1px solid; } p.legend { margin-bottom: 1em; } p.legend em { color: #C00; font-style: normal; } div.errors { margin: 0 0 10px 0; padding: 5px 10px; border: #FC6 1px solid; background-color: #FFC; } div.errors p { margin: 0; } div.errors p em { color: #C00; font-style: normal; font-weight: bold; } div.success { margin: 0 0 10px 0; padding: 5px 10px; border: #FC6 1px solid; background-color: #FFC; } div.success p { margin: 0; color:#006633} div.success li {list-style-type: none; } div.form-container form p { margin: 0; } div.form-container form p.note { margin-left: 170px; font-size: 90%; color: #333; } div.form-container form fieldset { margin: 10px 0; padding: 10px; border: #DDD 1px solid; } div.form-container form legend { font-weight: bold; color: #666; } div.form-container form fieldset div { padding: 0.25em 0; } div.form-container label, div.form-container span.label { margin-right: 10px; padding-right: 10px; width: 150px; display: block; float: left; text-align: right; position: relative; } div.form-container label.error, div.form-container span.error { color: #000; } div.form-container select.error, div.form-container div.error {background-color: #FEF;} div.form-container label em, div.form-container span.label em { position: absolute; right: 0; font-size: 120%; font-style: normal; color: #C00; } div.form-container input.error { border-color: #C00; background-color: #FEF; } div.form-container input:focus, div.form-container input.error:focus, div.form-container textarea:focus { background-color: #FFC; border-color: #FC6; } div.form-container div.controlset {margin: 3px} div.form-container div.controlset label, div.form-container div.controlset input { display: inline; float: none; } div.form-container div.controlset div { margin-left: 170px; } div.form-container div.buttonrow { padding-left: 430px; border: 1px solid #CCCCCC } div#wrapper {width: 700px ; margin-left: auto; margin-right: auto} pre {color:black; font-size: 10pt; font-weight: bold; margin-left: 30px} </style> </head> <body> <div id="wrapper"> <h1> Form Validation Lab</h1> <div class="form-container"> <? if ($_SERVER['REQUEST_METHOD'] == 'GET') : ?> <? if (displayWelcomeMsg) : ?> <p>Please fill in the form........</p> <? endif; ?> <? endif; ?> <? if ($displaySuccessMsg): ?> <div class="success"> <p>Thank you for your submission.</p> <ol> <? foreach($successMsgs as $key => $successMsg): ?> <li><?= $key ?> = <?= $successMsg ?> </li> <? endforeach; ?> </ol> </div> <? endif; ?> <? if ($dispErrorMsg) : ?> <div class="errors"> <p><em>Oops...the following errors were encountered</em></p> <ul> <? foreach ($errMsgs as $key => $errMsg): ?> <li><?= $errMsgs ?> </li> <? endforeach; ?> </ul> <p>Please correct the errors and re-submit this form.</p> </div> <? endif; ?> <form action="<?= $_SERVER['PHP_SELF'] ?>" method="post"> <input type="hidden" name="act" value="post"> <div class="buttonrow"> <input type="submit" value="Submit This Form " class="button" /> <a href="<?= $_SERVER['PHP_SELF'] ?>" >Start Again</a> </div> <p class="legend"><strong>Note:</strong> Required fields are marked with an asterisk (<em>*</em>)</p> <fieldset> <legend>User Details</legend> <div> <label for="uname" >User Name <em>*</em></label> <? if (isset($errMsgs['uname'])) echo 'class = "errors"' ?> <input id="uname" type="text" name="uname" value="<?=$_POST['uname'] ?>" /> (must be greater than 5 chars)</div> <div> <label for="email">Email Address </label> <input id="email" type="text" name="email" value="" /> </div> </fieldset> <fieldset> <legend>Submission</legend> <div> <label for="year">Year (YYYY) <em>*</em></label> <input id="year" type="text" name="year" <? if (isset($errMsgs['year'])) echo 'class = "errors"' ?> value="" size="4" maxlength="4" /> (4 digit number)</div> <div> <label for="date">Month (MM)</label> <input id="date" type="text" name="month" value="" size="4" maxlength="2" /> (number ranging from 1-12)</div> </fieldset> <fieldset> <legend>Preferences</legend> <div> <label for="type" >Province (Multiple Select) <em>*</em></label> <select name = "province[]" multiple size = "12" id="type" > <? foreach ($PROVINCES as $abbreviation => $longname); ?> <option value = "<?=$abbreviation ?> "></option> <? enfgoreach; ?> </select> </div> <div class= 'controlset' > <span class="label">Status (Mult Select)<em>*</em></span> <input name="status[]" id="approved" value="approved" type="checkbox" /> <label for="approved">Approved</label> <input name="status[]" id="pending" value="pending" type="checkbox" /> <label for="pending">Pending Application</label> <input name="status[]" id="actives" value="actives" type="checkbox" /> <label for="actives">Active Service</label> </div> <div class= 'controlset'> <span class="label"> Location <em>*</em></span> <input name="location" id="radio1" value="Garage" type="radio" /> <label for="radio1">Garage</label> <input name="location" id="radio2" value="Attic" type="radio" /> <label for="radio2">Attic</label> <input name="location" id="radio3" value="House" type="radio" /> <label for="radio3">House</label> </div> </fieldset> </form> <p>This debug info is here to help you. You are only required to display the POST array</p> <pre><?= print_r($_POST,true) ?> </pre> </div> </div> </body> </html> Similar TutorialsI am trying to add some simple validation to my form. I only wanter users to be able to enter 11 numbers into the number field or else it will say 11 digit numbers only. A validation to only allow users to input numbers anything else and it brings up an error. and finally i want to check the email string to make sure it has an @ and a (.) . How would i go about adding these validation techniques to this code? <?php if ($_SERVER['REQUEST_METHOD']=="POST"){ // Recipent Email $to="andrew@peppermintdigital.com"; $subject="Reply to Peppermint Invitation"; $title = $_POST['title']; $name = stripslashes($_POST['name']); $add1 = stripslashes($_POST['add1']); $add2 = stripslashes($_POST['add2']); $add3 = stripslashes($_POST['add3']); $add4 = stripslashes($_POST['add4']); $postcode = stripslashes($_POST['postcode']); $number = stripslashes($_POST['number']); $email = stripslashes($_POST['email']); $time = $_POST['time']; $from = ($_POST['name']) . "<".stripslashes($_POST['email']).">"; $subject = ($_POST['name']) . "<".stripslashes($_POST['email']).">"; // Email Message $message = "Name : $title $name. Address : $add1, $add2, $add3, $add4, $postcode. Phone Number : $number. Email : $email. Appointment Time : $time"; // Validation Begins // Add Erros To Array $errors = array(); // Check Form if (!$_POST['title']) $errors[] = "Title Required"; if (!$_POST['name']) $errors[] = "Name Required"; if (!$_POST['add1']) $errors[] = "Address Required"; if (!$_POST['add4']) $errors[] = "City Required"; if (!$_POST['postcode']) $errors[] = "Postcode Required"; if (!$_POST['number']) $errors[] = "Number Required"; if(!$_POST['number'] == 11) $errors[] = "Full Number Required"; if (!$_POST['email']) $errors[] = "Email Required"; if (!$_POST['time']) $errors[] = "Time Required"; // Display Errors if (count($errors)>0) { echo"<h1 class='fail'>"; foreach($errors as $err) echo "$err.\n"; echo"</h1>"; echo " <form method='post' action='#'> <table cellpadding='0' cellspacing='0' border='0'> <tr> <td class='form_results' colspan='2'> </td> </tr> <tr> <td class='form_left' valign='top'> <table width='200' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='title_left' valign='top'>Title</td> </tr> <tr> <td class='sname_left' valign='top'>Name</td> </tr> <tr> <td class='add_left' valign='top'>Address</td> </tr> <tr> <td class='post_left' valign='top'>Postcode</td> </tr> <tr> <td class='number_left' valign='top'>Phone Number</td> </tr> <tr> <td class='email_left' valign='top'>Email Address</td> </tr> <tr> <td class='time_left' valign='top'>Appointment Time</td> </tr> </table> </td> <td class='form_right' valign='top'> <table width='300' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='right_spacer'> <select name='title' class='select'> <option>Mr</option> <option>Mrs</option> <option>Ms</option> <option>Miss</option> </select> </td> </tr> <tr> <td class='right_spacer'><input type='text' name='name' class='field' value='$name' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add1' class='field' value='$add1' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add2' class='field' value='$add2' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add3' class='field' value='$add3' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add4' class='field' value='$add4' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='postcode' class='field' value='$postcode' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='number' class='field' value='$number' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='email' class='field' value='$email' /></td> </tr> <tr> <td class='right_spacer'> <select name='time' class='select'> <option>5.30 pm</option> <option>6.30 pm</option> <option>7.30 pm</option> </select> </td> </tr> </table> </td> </tr> <tr> <td class='form_buttom' colspan='2'> <input name='submit' type='submit' value='Submit' class='submit_button' /> </td> </tr> </table> </form> "; } else { // Build message headers $headers = "From: $from\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\""; // Send message if (@mail($to, $subject, $message, $headers)) echo "<h1 class='success'>Your message has been sent.</h1>"; else echo "<h1 class='fail'>Your message was not sent at this time.</h1>"; } } else { echo " <form method='post' action='#'> <table cellpadding='0' cellspacing='0' border='0'> <tr> <td class='form_results' colspan='2'> </td> </tr> <tr> <td class='form_left' valign='top'> <table width='200' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='title_left' valign='top'>Title</td> </tr> <tr> <td class='sname_left' valign='top'>Name</td> </tr> <tr> <td class='add_left' valign='top'>Address</td> </tr> <tr> <td class='post_left' valign='top'>Postcode</td> </tr> <tr> <td class='number_left' valign='top'>Phone Number</td> </tr> <tr> <td class='email_left' valign='top'>Email Address</td> </tr> <tr> <td class='time_left' valign='top'>Appointment Time</td> </tr> </table> </td> <td class='form_right' valign='top'> <table width='300' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='right_spacer'> <select name='title' class='select'> <option>Mr</option> <option>Mrs</option> <option>Ms</option> <option>Miss</option> </select> </td> </tr> <tr> <td class='right_spacer'><input type='text' name='name' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add1' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add2' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add3' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add4' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='postcode' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='number' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='email' class='field' /></td> </tr> <tr> <td class='right_spacer'> <select name='time' class='select'> <option>5.30 pm</option> <option>6.30 pm</option> <option>7.30 pm</option> </select> </td> </tr> </table> </td> </tr> <tr> <td class='form_buttom' colspan='2'> <input name='submit' type='submit' value='Submit' class='submit_button' /> </td> </tr> </table> </form> "; } ?> Hey everyone. I hope you can help me getting through this problem, because I have no idea of what else to try. I'm a web designer and sometimes modify Javascript, but my main focus is HTML and CSS, meaning I have no idea how to code in Javascript, but most importantly, how to write something from scratch in PHP. So I designed a form that works pretty well, and integrated a PHP and Javascript script to make it work. This is the form: Code: [Select] <form name="form" id="form" method="post" action="contact.php"> <p>Hello,</p> <p>My name is <input type="text" name="name">, from <input type="text" name="location">, and I'd like to get in touch with you for the following purpose:</p> <p><textarea name="message" rows="10" ></textarea></p> <p>By the way, my email address is <input type="text" name="email" id="email" placeholder="john@doe.com">, and I can prove I'm not a robot because I know the sky is <input type="text" name="code" placeholder="Red, green or blue?">.</p> <p title="Send this message."><input type="submit" id="submit" value="Take care."></p> </form> And this is the script, in an external file called contact.php: Code: [Select] <?php $name = check_input($_REQUEST['name'], "Please enter your name.") ; $location = check_input($_REQUEST['location']) ; $message = check_input($_REQUEST['message'], "Please write a message.") ; $email = check_input($_REQUEST['email'], "Please enter a valid email address.") ; if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {die("E-mail address not valid");} if (strtolower($_POST['code']) != 'blue') {die('You are definitely a robot.');} $mail_status = mail( "my@email.com", "Hey!", "Hello,\n\n$message\n\nRegards,\n\n$name\n$location", "From: $email $name" ); function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { show_error($problem); } return $data; } function show_error($myError) { ?> <html> <body> <b>Please correct the following error:</b><br /> <?php echo $myError; ?> </body> </html> <?php exit(); } if ($mail_status) { ?> <script language="javascript" type="text/javascript"> alert('Thank you for the message. I will try to respond as soon as I can.'); window.location = '/about'; </script> <?php } else { ?> <script language="javascript" type="text/javascript"> alert('There was an error. Please try again in a few minutes, or send the message directly to aalejandro@bitsland.com.'); window.location = '/about'; </script> <?php } ?> So what it does is this: if everything's OK, it sends an email with "Hey!" as the subject, "[name]" as the sender, "Hello, [message]. Regards, [name], [location]" as the body, and a popup saying the message was delivered appears. If something fails, it outputs the error in a new address, so the user will have to go back to the form and correct the error. What I actually want to happen is this: if everything's OK, a <p> which was hidden beneath the form appears saying the message was delivered, or, alternatively, make the submit button gray out and confirm the message was delivered. I found a script to make this happen, but with "Please wait...", so the user can't resubmit the form. If there's an error, I'd like another <p> which was hidden to appear with the specific error, so there'd be many <p>'s hidden with different IDs. If possible, I'd also like to change the CSS style of the input field, specifically changing the border color to red, so it'd be a change in class for the particular field. -- So in essence, I want the errors and the success messages to output in the same page as the form (without refresh), and a change of class in the input fields that have an error. Thanks in advance, and please let me know if it'll be possible. Hi all, I have the below which is meant to check if the required fields in a form have been submitted, however when submit is clicked, even with no values in the boxes, the form submits as normal. <?php error_reporting(E_ALL); ini_set('display_errors', '1'); include_once ('formvalidator.php'); ?> <link href="../Styles/form_dark.css" rel="stylesheet" type="text/css" /> <?php $show_form=true; if(isset($_POST['submit'])) { $validator = new FormValidator(); $validator->addValidation("user_name","req","Please fill in Name"); $validator->addValidation("user_password","req","Please enter a password"); $validator->addValidation("user_email","email", "The input for Email should be a valid email value"); $validator->addValidation("user_email","req","Please fill in Email"); if($validator->ValidateForm()) { echo "<h2>Validation Success!</h2>"; $show_form=false; } else { echo "<B>Validation Errors:</B>"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p>$inpname : $inp_err</p>\n"; } } } if(true == $show_form) { ?> <form class="dark" action="regdo.php" method="post" > <ol> <li> <fieldset> <legend>User Registration</legend> <ol> <li> <label for="user_name">Username</label> <input type="text" id="user_name" name="user_name" value="" /> </li> <li> <label for="user_email">E-Mail Address</label> <input type="text" id="user_email" name="user_email" value="" /> </li> <li> <label for="user_password">Password</label> <input type="password" id="user_password" name="user_password" value="" /> </li> </ol> </fieldset> </li> </ol> <p style="text-align:right;"> <input type="reset" value="CANCEL" /> <input type="submit" value="OK" /> </p> </form> <?php }//true == $show_form ?> Can anyone explain what the problem is? Cheers Hi, I am searching for a basic, easy to implement php form validation script that checks if the user has filled out a field, if they havent to tell them so. i have tried basic if statements but it refreshes the page and all the other fields that were filled in are clear. Anyone know of any tricks or scripts that are good? Thanks in advance. Hi Guys Simple question. Can anyone tell me why this doesn't work please? Code: [Select] $test = "<HEELOOOO"; $test2 = filter_var("$test", FILTER_SANITIZE_STRING); echo $test2; When I run this get I get nothing echoed back, not even in the source. So can the filter function not be used like this? I thought it would encode the special character and return it but I must be missing something simple here! Thanks, Drongo Not sure what I am missing. When submitted gives white page with no submission. Error check is not showing anything. global $userdata, $current_user; $tablename=kudos_table_name(); // Functions to filter user inputs function filterkudoagent($field){ // Sanitize user name $field = filter_var(trim($field), FILTER_SANITIZE_STRING); // Validate user name if(filter_var($field, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z-\s]+$/")))){ return $field; } else { return FALSE; } } function filterkudocust($field){ // Sanitize user name $field = filter_var(trim($field), FILTER_SANITIZE_STRING); // Validate user name if(filter_var($field, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z-\s]+$/")))){ return $field; } else { return FALSE; } } function filterString($field){ // Sanitize string $field = filter_var(trim($field), FILTER_SANITIZE_STRING); if(!empty($field)){ return $field; } else{ return FALSE; } } $kudoagentErr = $agentlocErr = $kudoclientErr = $kudocustErr = $kudomsgErr = $kudoadnErr = ""; $kudoagent = $agentloc = $kudoclient = $kudocust = $kudomsg = $kudoadn = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if(empty($_POST["kudoagent"])){ $kudoagentErr = "Please enter agent name."; } else{ $kudoagent = filterkudoagent($_POST["kudoagent"]); if($kudoagent == FALSE){ $kudoagentErr = "Please enter a valid agent name."; } } if(empty($_POST['agentloc'])){ $agentlocErr = "You must select a location"; } if(empty($_POST['kudoclient'])){ $kudoclientErr = "You must select a queue"; } if(empty($_POST["kudocust"])){ $kudocustErr = "Please enter customer name."; } else{ $kudocust = filterkudocust($_POST["kudocust"]); if($kudocust == FALSE){ $kudocustErr = "Please enter a valid customer name."; } } if(empty($_POST["kudomsg"])){ $kudomsgErr = "Please enter the kudos."; } else{ $kudomsg = filterString($_POST["kudomsg"]); if($kudomsg == FALSE){ $kudomsgErr = "Please enter a valid kudos."; } } if(empty($_POST["kudoadminname"])){ $kudoadnErr = "Please enter the posters name."; } else{ $kudoadn = filterkudocust($_POST["kudoadminname"]); if($kudoadn == FALSE){ $kudoadnErr = "Please enter a valid posters name."; } } if (isset($_POST['kudoagentid']) && trim($_POST['kudoagentid']) != '') { $kudoagidErr = "Enter Agent ID or leave blank"; } else { $kudoacctErr = ""; } if (isset($_POST['kudoacct']) && trim($_POST['kudoacct']) != '' && !ctype_digit($_POST['kudoacct'])) { $kudoacctErr = "Only numbers are permitted or leave blank"; } else { $kudoacctErr = ""; } if(empty($kudoagentErr) && empty($kudocustErr) && empty($kudomsgErr) && empty($agentlocErr) && empty($kudoclientErr) && empty($kudoadnErr)){ global $wpdb; $table = $tablename; $kudokey = randkey(); $kudoposted = date("Y-m-d H:i:s"); $data = array( 'kudoid' => '', 'kudomsg' => $_POST['kudomsg'], 'kudoagent' => $_POST['kudoagent'], 'kudoagentid' => $_POST['kudoagentid'], 'kudocust' => $_POST['kudocust'], 'kudoacct' => $_POST['kudoacct'], 'kudoclient' => $_POST['kudoclient'], 'kudoloc' => $_POST['agentloc'], 'kudoentry' => $kudoposted, 'kudoadmin' => $_POST['kudoadminname'], 'kudopic' => $_POST['kudobanner'], 'kudostatus' => '1', 'kudokey' => $kudokey, ); $format = array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ); $success=$wpdb->insert( $table, $data, $format ); if($success){ echo "<blockquote class=\"otro-blockquote\">"; echo nl2br($_POST['kudomsg']); echo "<span>"; echo "<b>Kudos for:</b> " .$_POST['kudoagent']. " " .$_POST['kudoagentid']. ", ".$_POST['agentloc']; echo "<br>By: ".$_POST['kudocust']. ", " . date("F j, Y g:i a", strtotime($kudoposted)); echo "<br/>" .$_POST['kudoacct']; echo "<br/> Submitted By: " .$_POST['kudoadminname']; echo "</span></blockquote>"; $urlparts = parse_url(home_url()); $kudourl = $urlparts['host']; echo "<div class='success_msg'>Kudos Submitted</div>"; } } } else { ?> <h3>Add Kudos - No Notification Sent</h3> <b>* states required</b> <form name="kudos_form" id="submitkudos" method="post" action="" enctype="multipart/form-data"> <table class="addkudotable"> <tr> <td>Agent Name *</td> <td> </td> <td><input name="kudoagent" type="text" value="<?php echo $_POST['kudoagent']; ?>"/> <?php echo "<div class='note'>".$kudoagentErr."<br/>";?> </td> </tr> <tr> <td>Agent ID</td> <td></td> <td><input name="kudoagentid" type="text" value="<?php echo $_POST['kudoagentid']; ?>" /> <?php echo "<div class='note'> </div>";?> </td> </tr> <tr> <td>Agent Location *</td> <td></td> <td><select name="agentloc" size="1"> <option value="<?php echo $_POST['agentloc']; ?>"><?php echo $_POST['agentloc']; ?></option> <option></option> <option value="Amherst Center">Amherst Center</option> <option value="Charlottetown Center">Charlottetown Center</option> <option value="Kingston Center">Kingston Center</option> </select> <?php echo "<div class='note'>".$agentlocErr."</div>";?> </td> </tr> <tr> <td>Agent Queue *</td> <td></td> <td><select name="kudoclient" size="1"> <option value="<?php echo $_POST['kudoclient']; ?>"><?php echo $_POST['kudoclient']; ?></option> <option value=""></option> <option value="AR">AR</option> <option value="Eastlink Tech Support">Eastlink Tech Support</option> <option value="PNI">PNI</option> </select> <?php echo "<div class='note'>".$kudoclientErr."</div>";?> </td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td>Customer Name *</td> <td></td> <td><input name="kudocust" type="text" value="<?php echo $_POST['kudocust']; ?>"/> <?php echo "<div class='note'>".$kudocustErr."</div>";?> </td> </tr> <tr> <td>Customer Account #</td> <td></td> <td><input name="kudoacct" type="text" value="<?php echo $_POST['kudoacct']; ?>" /> <?php echo "<div class='note'>".$kudoacctErr."</div>";?> </td> </tr> <tr> <td>Kudos *</td> <td></td> <td><textarea cols="50" name="kudomsg" rows="5"><?php echo $_POST['kudomsg']; ?></textarea> <?php echo "<div class='note'>".$kudomsgErr."</div>";?> </td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td>Choose Image</td> <td></td> <td><select onchange="$('#imageToSwap').attr('src', this.options[this.selectedIndex].value);" name="kudobanner"> <option value="<?php echo plugins_url(); ?>/img/kudos/1.jpeg" selected>Kudos 1</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/2.jpg">Kudos 2</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/3.png">Kudos 3</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/4.png">Kudos 4</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/5.png">Kudos 5</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/6.jpg">Kudos 6</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/7.jpg">Kudos 7</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/8.jpg">Kudos 8</option> <option value="<?php echo plugins_url(); ?>/kudos/img/kudos/9.png">Kudos 9</option> </select></td> </tr> <tr> <td>Agent submitting Kudos</td> <td></td> <td><input name="kudoadminname" type="text" value="<?php echo $_POST['kudoadminname']; ?>"> <?php echo "<div class='note'>".$kudoadnErr."</div>";?></td> </tr> <tr> <td> </td> <td><input type="hidden" name="action" value=""/></td> <td></td> </tr> <tr> <td><button type="submit" value="submit" class="aciformbutton" name="submit" />Submit Kudos</button> <td></td> <td><button type="reset" value="reset" class="aciformbutton">Start Over</button></td> </tr> </table> <input type="hidden" value="" name="kudoentry"> </form> <script> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <?php echo "<img id=\"imageToSwap\" class=\"profile\" src=" . plugins_url() . "/kudos/img/kudos/1.jpeg>"; }
I am asking for some simple help, please. :-) I have a form that I would like to validate very specific information on - without having it validate in the php and loose what the client just put into the site. I have found an example in this "validation" process. However, when I open this up in Dreamweaver CS4, I have an error on line 67 as a syntex error. I am unable to see where this would be. All I need is a verification on the name, the phone number, and the email address. Here is what I have so far.... **This is contact form** Code: [Select] <script language="JavaScript"> function checkForm() { var cname, cemail, cphone with(window.document.Contact1) { cname = name; cemail = EmailFrom; cphone = phone; } if(trim(cname.value) == '') { alert('Please enter your name'); cname.focus(); return false; } else if(trim(cemail.value) == '') { alert('Please enter your email'); cemail.focus(); return false; } else if(!isEmail(trim(cemail.value))) { alert('Email address is not valid'); cemail.focus(); return false; } else if(trim(cphone.value) == '') { alert('Please enter message subject'); csubject.focus(); return false; } } else { cname.value = trim(cname.value); cemail.value = trim(cemail.value); cphone.value = trim(cphone.value); return true; } } function trim(str) { return str.replace(/^\s+|\s+$/g,''); } function isEmail(str) { var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag| ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg| bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg| ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk| dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb| gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn| hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg| kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly| ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum| mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu| nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa| re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st| su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz| ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za| zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i; return regex.test(str); } </script> Below is the php file that I am using.... Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Emailing Form Data</title> </head> <body> <?php ini_set ("display_errors", "1"); error_reporting(E_ALL); //declaration of variables $EmailFrom = trim(stripslashes($_POST['EmailFrom'])); $EmailTo = "ornclo@aol.com"; $Subject = "Women United Contact"; $Name = trim(stripslashes($_POST['name'])); $Address = trim(stripslashes($_POST['address'])); $City = trim(stripslashes($_POST['city'])); $State = trim(stripslashes($_POST['state'])); $Phone1 = trim(stripslashes($_POST['phone1'])); $Phone2 = trim(stripslashes($_POST['phone2'])); $Phone3 = trim(stripslashes($_POST['phone3'])); $email = trim(stripslashes($_POST['email'])); foreach ($_POST['visit'] as $value) { $Church = trim(stripslashes($value)); } foreach ($_POST['hear'] as $hear) { $About = trim(stripslashes($hear)); } foreach ($_POST['help'] as $help) { $Ask = trim(stripslashes($help)); } $Comments = trim(stripslashes($_POST['comments'])); // validation $validationOK=true; if (($EmailFrom)=="") $validationOK=false; if (($Name)=="") $validationOK=false; if (($Phone1)=="") $validationOK=false; if (($Phone2)=="") $validationOK=false; if (($Phone3)=="") $validationOK=false; if (($email)=="") $validationOK=false; if (($Comments)=="") $validationOK=false; if (!$validationOK) { print "<meta http-equiv=\"refresh\" content=\"0;URL=WUerror.html\">"; exit; } // prepare email body text $Body = "\n"; $Body .= "Name: "; $Body .= $Name; $Body .= "\n"; $Body .= "Address: "; $Body .= $Address; $Body .= "\n"; $Body .= "City: "; $Body .= $City; $Body .= "\n"; $Body .= "State: "; $Body .= $State; $Body .= "\n"; $Body .= "Phone: "; $Body .= $Phone1; $Body .= "-"; $Body .= $Phone2; $Body .= "-"; $Body .= $Phone3; $Body .= "\n"; $Body .= "Attended Church of God?: "; $Body .= $Church; $Body .= "\n"; $Body .= "How did you hear about us?: "; $Body .= $About; $Body .= "\n"; $Body .= "What can we do to help you?: "; $Body .= $Ask; $Body .= "\n"; $Body .= "Comments: "; $Body .= $Comments; $Body .= "\n"; // send email $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>"); // redirect to success page if ($success){ print "<meta http-equiv=\"refresh\" content=\"0;URL=WUok.html\">"; } else{ print "<meta http-equiv=\"refresh\" content=\"0;URL=WUerror.html\">"; } ?> </body> </html> Unless there is a way to change this line: print "<meta http-equiv=\"refresh\" content=\"0;URL=WUerror.html\">"; to have it keep in the same window - or even possibly open a NEW window with the "error.html" - that would be fine as well. Again - when I open up Contact1.html in DW CS4, I get a syntext error on line 67. When I use just straight form, it opens to new window with php - > error.html, which in turns looses everything the client just typed. Any help is greatly appreciated and thank you in advance. Blessings! If asked, I can attach the files if needed as well, but the code is pretty self-explain. Hi there, I've got a HTML textarea with the name attribute of 'review' and I've posted this into a variable called $review. I want to say if the characters are less than 30, please enter more words etc. The problem is, I get the if statement's error even when there are more than 30 characters. Can anyone figure out why I'm getting this? Code: [Select] if ($review < 30){ echo '<p class="red">Review is too short, please enter at least 15 words</p>'; } I have a pretty complicated script i'm trying to work on but i'm not having much luck. Basically what needs to happen is i need part of my script to check a database and count 2 different sets of data for the current date, then if both conditions are true then submit the users name, current date, and a time id to the database it checks, and then submit the form data to a text file. i'll try and map it out. check database for how many times the username appears for current date if it is less than 3 move to next validation if it is false, give error message check database for how many times the time id appears for current date if it is less than 30 move to next section if it is false, give error message send username, timestamp (of clients computer), and time id to the 'totals' database and send form data to text file. So.... thats it in a nutshell. I'm going to have to go into my 'cart' page and edit in a row to have the order#, username, timestamp, and time id before the rest of the order details I want in my form to validate on the fly(when the user enters the user name) to validate if the user name exists or not. How am i supposed to check if the field name is the same or not with a name in the database.Should i use ajax or javascript? is there any simple example on how to do that. Hi all, Im trying to add validation to a form to allow PHP to check before its sends the values to another page for them to be uploaded to a database. The problem i have is that i have taken a, i thought simple PHP validating script off the net and i cant seem to get it to work, its just giving me a blank page. I dont know if the script is outdated, i dont think it is. The script is he Code: [Select] <?php include("validation.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Test Area</title> <link rel="stylesheet" href="test.css" type="text/css" media="screen" /> </head> <body> <div id="container"> <h1>Add a Product</h1> <?if(isset($_POST['send'])&amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;(!validateModel($_POST['model']) || !validatePrice($_POST['price']) || !validateDescription($_POST['description']) ) ):?> <div id="error"> <ul> <?if(!validateModel($_POST['model'])):?> <li><strong>Invalid Name:</strong> We want names with more than 3 letters!</li> <?endif?> <?if(!validatePrice($_POST['price'])):?> <li><strong>Invalid E-mail:</strong> Type a Valid Price!</li> <?endif?> <?if(!validateDescription($_POST['description'])):?> <li><strong>Invalid message:</strong> Type a message with at least with 10 letters</li> <?endif?> </ul> </div> <?elseif(isset($_POST['send'])):?> <div id="error" class="valid"> <ul> <li><strong>Congratulations!</strong> All fields are OK ;)</li> </ul> </div> <?endif?> <form method="post" id="customForm" action="" enctype="multipart/form-data"> <div> <label for="model">Model Number</label> <input id="model" name="model" type="text" /> <span id="modelInfo">Please enter your Product Model Number!</span> </div> <div> <label for="product">Product</label> <select class="products" name="products"> <option value="0">Please select an option below</option> <option value="1">19" LCD TV</option> <option value="2">22" LCD TV</option> <option value="3">26" LCD TV</option> <option value="4">32" LCD TV</option> <option value="5">37" LCD TV</option> <option value="6">42" LCD TV</option> <option value="7">37" Plasma TV</option> <option value="8">42" Plasma TV</option> <option value="9">46" Plasma TV</option> <option value="10">50" Plasma TV</option> <option value="11">54" Plasma TV</option> <option value="12">58" Plasma TV</option> <option value="13">Wall Bracket</option> <option value="14">Home Cinema System</option> <option value="15">Bluray Home Cinema System</option> <option value="16">DVD Recorder</option> <option value="17">DVD Player</option> <option value="18">DVD Portable</option> <option value="">Bluray Recorder</option> <option value="">Bluray Player</option> <option value="">Bluray Portable</option> <option value="">Projector</option> <option value="">37" LCD TV</option> <option value="">42" LCD TV</option> <option value="">Personal Video Recorder (PVR)</option> <option value="">3D Technology</option> <option value="">Upright Cleaner</option> <option value="">Cylinder Cleaner</option> <option value="">DECT Phone</option> <option value="">DECT Answer Phone</option> <option value="">Washing Machines</option> <option value="">Tumble Dryers</option> <option value="">Dishwashers</option> <option value="">Fridge-Freezers</option> <option value="">Freezers</option> <option value="">Refridgerators</option> <option value="">Microwave (Solo)</option> <option value="">Microwave (Grill)</option> <option value="">Microwave Combination</option> <option value="">Kettles</option> <option value="">Toasters</option> <option value="">Irons</option> <option value="">Breadmakers</option> <option value="">Microsystems</option> <option value="">Minisystems</option> <option value="">CD, Radio and Cassette Players</option> <option value="">Pure Radios</option> <option value="">Dimplex Fires</option> <option value="">Convector Heaters</option> <option value="">Fan Heaters</option> <option value="">Mens Shavers/Grooming</option> <option value="">Ladies Shavers/Beauty</option> <option value="">Straighteners</option> <option value="">Epilators</option> <option value="">Stylish Cameras</option> <option value="">Super Zoom Cameras</option> <option value="">SD Camcorders</option> <option value="">HD Camcorders</option> <option value="">HDD Camcorders</option> <option value="">Bluray Discs</option> <option value="">DVD Discs</option> <option value="">Leads</option> <option value="">Mini DV Tapes</option> <option value="">SD/SDHC/SDXC Cards</option> </select> <span id="productInfo">Please choose a Product Title!</span> </div> <div> <label for="price">Price</label> <input id="price" name="price" type="text" /> <span id="priceInfo">Please enter a Price!</span> </div> <div> <label for="photo">Image</label> <input style="font-size:13px;" class="file" name="photo" type="file" /> <span id="photoInfo">Please choose an Image!</span> </div> <div> <label for="message">Description</label> <textarea id="description" name="description" cols="" rows=""></textarea> </div> <div> <input id="send" name="send" type="submit" value="Send" /> </div> </form> </div> </body> </html> This is the validation file: <?php function validateModel($model){ //if it's NOT valid if(strlen($model) < 4) return false; //if it's valid else return true; } function validatePrice($price){ //if it's NOT valid if(strlen($price) < 4) return false; //if it's valid else return true; } function validateDescription($description){ //if it's NOT valid if(strlen($description) < 10) return false; //if it's valid else return true; } ?> I can't spot the problem, any suggestions? I'm trying to get validation messages to display on the same page as my login form without any PHP within my login page, is that possible?
Hello! I was wondering if I could have some help with some form validation. In my insert script, I have: <label for="text"><br /> <br /> Question Text:</label> <textarea name="text" id="text" cols="45" rows="5"> </textarea> Then in a separate script, I input the data into a database: $data = array('text' => $_POST['text'] 'question_type' => $_POST['question_type'], 'solution' => $_POST['solution'], 'author_id' => $_POST['author'], 'public_access' => $_POST['public_access']); In this database script, I'd like to check if the text field was "posted": if it's empty I'd then like to print "Required field" on my original script. First, if there's nothing to be posted from the text field, I want to stop the database script and return before entering a blank field into my database. Then, it would be great if I could print a "Required field" message in the original script. Thanks in advance for your help! Hi, I am trying to setup a PHP script that will validate an html form. The form and the PHP script are separate from each other. The code that I have was modified from a tutorial on YouTube. The example used there works but as I have began to tailor it to my purpose, it is now broke. I just added one line for validation to simplify troubleshooting. If I find an empty field on the form, I would like to display the error message on the form itself rather than start a new html page with the PHP script. I am not sure if that is possible. Here is my form: http://www.tallfirshoa.com/adform.htm YouTube videos that I was working from. The video's example has the form and PHP combined as one. In my case, I need the form and PHP separate. http://www.youtube.com/watch?v=yuLpSospbBk&feature=search http://www.youtube.com/watch?v=LF5zTWthpn0&feature=search The code works fine if I leave out the validation. As soon as I add if(!$fname), the script becomes broken. I'm guessing that it has something to do with $errorstring and how it works. I am new to PHP and have tried as many things as I can think of but I can't make any forward progress. Thanks for your help! Rob Code: [Select] <html> <h1>Tall Firs Ad Submission</h1> <?php if ($_POST['submit']) { //Get form data $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $displayemail = $_POST['displayemail']; $phone = $_POST['phone']; $category = $_POST['category']; $description = $_POST['description']; //Declare variables $to = "email@gmail.com"; $subject = "Request"; $headers = "From: $email \r\n Reply-To: $email"; } //Setup form validation $errorstring = "" //default value of error string //Begin validation if (!$fname) $errorstring = $errorstring."First Name<br>"; ?> </html> Hi all! Im trying to modify a script so that when a user submits data on a form if there are any errors it flags all errors and not just the first one the script comes to and 'dies'. Heres the form code <?php session_start(); ?> <!--//-----------------------------------------------------------------------------------------------+ | // Sample AJAX web form By: Codex-m | // http://www.php-developer.org | // You are free to use and improve this script provided you link to author web site: http://www.php-developer.org | //--------------------------------------------------------------------------------------------------------------> <html> <head> <title>Sample AJAX Web Form</title> <script type="text/javascript" src="prototype.js"></script> <script type="text/javascript"> function sendRequest() { new Ajax.Request("ajaxvalidate.php", { method: 'post', parameters: 'name='+$F('name')+'&phonenumber='+$F('phonenumber')+'&age='+$F('age')+'&captcha='+$F('captcha'), onComplete: showResponse }); } function showResponse(req){ $('show').innerHTML= req.responseText; } </script> <style type="text/css"> P.yellow {background-color: #ffff00;} </style> </head> <body> <h3>This is a sample PHP web form with AJAX validation</h3> Please complete the form below and then press "Submit button".<br /> <br /><br /> <form action="/ajaxwebform/ajaxvalidate.php" method="post" onsubmit="return false;"> Enter your Full Name, First name and Last name ONLY (Example: John Doe)<br /> <input style="background-color: #FFFFC0" type="text" name="name" id="name" size="50"> <br /><br /> Enter your Phone number (numbers only, no dashes and spaces)<br /> <input style="background-color: #FFFFC0" type="text" name="phonenumber" id="phonenumber" size="35"> <br /><br /> Enter your Age (Numbers only)<br /> <input style="background-color: #FFFFC0" type="text" name="age" id="age" size="50"> <br /><br /> <img src="/ajaxwebform/captcha.php" /> <br /> Enter the Captcha as shown above: <br /> <br /> <input style="background-color: #FFFFC0" type="text" name="captcha" id="captcha" size="10"> <br /> <br /> <input type="submit" value="Submit" onClick="sendRequest()"> </form> <br /> This form will validate your data entry using AJAX. If you are correct with your data entry, the entire information entered will be shown in this page without reloading. <br /> <br /><br /> <p class="yellow" id="show"></p> </body> </html> Heres the php validating code <?php session_start(); ?> <!--//-----------------------------------------------------------------------------------------------+ | // Sample AJAX web form By: Codex-m | // http://www.php-developer.org | // You are free to use and improve this script provided you link to author web site: http://www.php-developer.org | //--------------------------------------------------------------------------------------------------------------> <?php //start session to recover captcha answers //connect to database $username = "root"; $password = ""; $hostname = "localhost"; $database = "newdb"; $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); $selected = mysql_select_db($database,$dbhandle) or die("Could not select $database"); //extract form inputs $name =$_POST['name']; $phonenumber =$_POST['phonenumber']; $age =$_POST['age']; $usercaptchaanswer =$_POST['captcha']; $correctcaptcha = $_SESSION['answer']; //sanitize early for any possible MySQL entry $name = mysql_real_escape_string(stripslashes(trim($name))); $phonenumber = mysql_real_escape_string(stripslashes(trim($phonenumber))); $age = mysql_real_escape_string(stripslashes(trim($age))); $usercaptchaanswer = mysql_real_escape_string(stripslashes(trim($usercaptchaanswer))); $correctcaptcha = mysql_real_escape_string(stripslashes(trim($correctcaptcha))); Validate captcha entry if ($correctcaptcha != $usercaptchaanswer) { echo 'ERROR: You have entered wrong captcha code'; die (); } //Step 2 of data validation: check for blank entries if (empty($name)) { //name field is blank echo 'ERROR: The name field is empty.'; die (); } if (empty($phonenumber)) { //phone field is blank echo 'ERROR: The phone field is empty.'; die (); } if (empty($age)) { //age field is blank echo 'ERROR: The age field is empty.'; die (); } if (empty($usercaptchaanswer)) { captcha field is blank echo 'ERROR: The captcha field is empty.'; die (); } //Step 3 of data validation: Ensuring correct format //Step 3.1 validate full name, presence of first name and last name $mystring = $name; $findme = ' '; $pos = strpos($mystring, $findme); $actualposition =$pos + 1; //count strings $count =strlen($mystring); //count the number of characters for the first name $countfirstname = $actualposition - 1; //count the number of characters for the last name $countlastname = $count - $actualposition; //detect if full name has middle name $posmid= strpos($mystring,$findme,$actualposition) + 1; $middleadjust = $posmid - $actualposition; $purealpha = str_replace(" ", "x", $mystring); if ($actualposition==1) { echo 'ERROR: You either forgot your first name or your last name.'; die (); } if ($countfirstname <2) { echo 'ERROR: You are using an invalid first name, it should contain more than one character.'; die (); } if ($countlastname <2) { echo 'ERROR: You are using an invalid last name, it should contain more than one character.'; die (); } if ($middleadjust >= 2) { echo 'ERROR: You should not be using a middle name, please use only first name and last name.'; die (); } if (!(ctype_alpha($purealpha))) { echo 'ERROR: Full name can only consist of alphabetic characters.'; die (); } //Step 3.2 Validate phone number if (!(ctype_digit($phonenumber))) { echo 'ERROR: A phone number should consist of numerical digits only and no spaces between numbers'; die (); } //Step 3.3 Validate age if (!(ctype_digit($age))) { echo 'ERROR: Your age should consist of numerical digits only and no spaces between numbers'; die (); } //Step 4. If all data entry is correct, show results in another page, assigned all values to sessions echo 'Thank you for the correct data entry, below are the information entered:'; echo '<br />'; echo 'Your full name is: '.$name; echo '<br />'; echo 'Your phone number is: '.$phonenumber; echo '<br />'; echo 'Your age is: '.$age; echo '<br />'; echo '<a href="/ajaxwebform/ajaxwebformtest.php">Click here to enter another data.</a>'; $_SESSION = array (); session_destroy (); mysql_close($dbhandle); ?> Hi, I currently have the following code in my form processing script: Code: [Select] $string_exp = "/^[A-Za-z .'-]+$/"; $error_missing = 'This field is required'; if(!preg_match($string_exp,$Name)) { $errors[] = $error_missing; } if(!preg_match($string_exp_number,$Phone)) { $errors[] = $error_missing; } if(is_array($errors)) { echo 'Your message could not be sent due to the following errors:'; while (list($key,$value) = each($errors)) { echo '<span class="error">'.$value.'</span><br />'; } If the user enters no data into the required fields, the script prevents the form from being submitted and displays an error. At present the errors for all the required fields are displayed in a long list at the top of my HTML form e.g. This field is required This field is required What I want to do, is place the error message under each required field e.g. this http://coreyworrell.com/assets/uploads/images/ajax_contact_form.png instead of this http://cdn1.1stwebdesigner.com/wp-content/uploads/2010/02/validation-ajax-css-form.jpg What do I need to do? My form looks similar to this at the moment: Code: [Select] <div id="log"> <div id="log_res"> </div> </div> <form id="contact" name="contact" method="post" action="process.php"> <label>Name</label> <input type="text" name="Name" id="Name" tabindex="1" /> <label>Email</label> <input type="text" name="Phone" id="Phone" tabindex="2" /> </form> The error messages are placed in the <div> section at the top of the form (using ajax) Okay with some help I was able to create a working guestbook! How ever I need a bit of help with validation. I would like to have it so that when someone doesn't fill out a required field a message is displayed next to the improperly filled out field. How would I go about adding this to my form or process code? So for example: if someone doesn't fill out the "name" field and clicks "sign" it will not submit but instead will display a message such as "Please fill out your name" next to the form field. Also will I am here I wanted to ask. How can I make it so that when a non-required field is left empty and posted it will fill that section out with default text? So for example: if someone decides they do not wish to fill out the "Favorite part of my site" or "Favorite Pat Song" field than submits the form than it will fill that section with a default message like this: Posted by: someone (someone@domain.com) 2011/04/09 Favorite Pat Song: -- Favorite Part of the Site: -- comments here And I promise this is my very last question. I would like for email to be required but would like to allow the user to decide whether it is kept private or not. How do I make it so that when someone doesn't type their email in it does like what I stated above, it will show a message next to the field telling them to fill out a valid email but also if they select to keep their email private it will than post a default value in place of where the email would have been. for example: if the email field is left empty or is an invalid email it will display a message such as "Please fill out a valid email address" next to the form field. and than if they do so but also check the "private" box it will post their message in the guestbook with a default value in place of the email like this: Posted by: someone (Private) 2011/04/09 Favorite Pat Song: -- Favorite Part of the Site: -- comments here so that was a lot here's my guestbook code: Code: [Select] <?php <span style='color:#ff0000'><b>*</b></span><span> = required field</span><br /><br /> <form name='guestbook' action='process.php' method='post'> <table width='550' border='0' cellspacing='2' cellpadding='0'> <tr valign='top'> <td width='550px' class='what'><span style='color:#ff0000'><b>*</b></span> Your Name:</td> <td width='550px'><input name='name' type='text' id='name' size='32' /></td> </tr> <tr valign='top'> <td width='550px' class='what'><span style='color:#ff0000'><b>*</b></span> Email Address:</td> <td width='550px'><input name='email' type='text' id='email' size='32' /><input type='checkbox' name='private' value='Private' />Private</td> </tr> <tr valign='top'> <td width='550px' class='what'>Your Favorite Pat Song?:</td> <td width='550px'><input name='song' type='text' id='song' size='32' /></td> </tr> <tr valign='top'> <td width='550px' class='what'>Your Favorite Part of my Site?:</td> <td width='550px'><input name='part' type='text' id='part' size='32' /></td> </tr> <tr valign='top'> <td width='550px' class='what'><span style='color:#ff0000'><b>*</b></span> Comment:</td> <td width='550px'><textarea name='comments' cols='28' rows='6' id='comments' class='bodytext'></textarea></td> </tr> <tr> <td class='bodytext'> </td> <td align='left' valign='top'><input name='submit' type='submit' class='btn' value='Sign' /></td> </tr> </table> </form>"; }else{ $connect = mysql_connect("127.0.0.1","patben_admin","pepsi_1990") or die('Error connecting'); $db = mysql_select_db("patben_db") or die('Error selecting db'); $query = mysql_query("SELECT * FROM guestbook order by id desc"); $num_rows = mysql_num_rows($query); if($num_rows > 0) { //display entries while($row = mysql_fetch_array($query)){ echo ' <table> <tr> <td> <b>Posted by:</b> '.$row['name'].' ('.$row['email'].')<br /> <b>'.$row['date'].'</b><br /> <b>Favorite Pat Song:</b> '.$row['song'].'<br /> <b>Favorite Part of the Site:</b> '.$row['part'].' </td> </tr> <tr> <td> '.nl2br($row['comments']).' <hr /> </td> </tr> </table>'; } }else{ echo "No Entries... <a href='guestbook.php?page=sign'>Be the first!</a>"; } } ?> and here's the code that processes the form (separate file): Code: [Select] <?php if($_POST['submit']) { $connect = mysql_connect('127.0.0.1','patben_admin','pepsi_1990') or die('Error connecting'); $db = mysql_select_db('patben_db') or die('Error selecting db'); $date = date("Y-m-d"); $name = strip_tags($_POST['name']); $email = strip_tags($_POST['email']); $song = strip_tags($_POST['song']); $part = strip_tags($_POST['part']); $comments = nl2br($_POST['comments']); $query = mysql_query("insert into guestbook values('','$date','$name','$email','$song','$part','$comments')"); header("location: guestbook.php"); }else{ header("location: guestbook.php"); } ?> I have not added a section in my database for the check box so I am also unsure how to do that (if I need to). Any help would be greatly appreciated! Thank you Hi. I'm new to PHP and have a problem with some form validation. The code below is my contact form. It was working until I added a dropdown list and checkbox. For all the other fields I created an input variable using the 'name' attribute to reference the data entered into the input fields and the validation appeared to work and an email was sent to the appropriate email address. For the checkbox field I have also created a 'name' attribute but don't know whether this is right way to confirm whether the box has been checked? For the field with a dropdown selection I have used the option 'selected', but again, don't know whether this is right or not. Now when I enter valid data into all the fields, select a value from the dropdown and check the checkbox, I get an error message stating that I need to fill in all the form fields. I am pretty sure it is to do with the way I have tried to pick up the data from dropdown list and the checkbox, but can't figure out what it is. Any help would be much appreciated. Thanks in advance.
<?php echo file_get_contents('header.php'); ?> <?php // Message Vars $msg = ''; $msgClass = ''; // Check to see if the form has been submitted if(filter_has_var(INPUT_POST, 'submit')) { //Input Data Variables $firstname = htmlspecialchars($_POST['firstname']); $lastname = htmlspecialchars($_POST['lastname']); $phonenumber = htmlspecialchars($_POST['phonenumber']); $email = htmlspecialchars($_POST['email']); $selected = htmlspecialchars($_POST['selected']); $message = htmlspecialchars($_POST['message']); $checkbox = htmlspecialchars($_POST['checkbox']); //Check required fields if(!empty($firstname) && !empty($lastname) && !empty($phonenumber) && !empty($email) && !empty($selected) && !empty($message) && !empty($checkbox)) { // If passed, check email address if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) { //If failed, Email address is not valid $msg = 'Please use a valid email address'; $msgClass = 'alert-danger'; } else { //Recipient email address and information to be sent to them $toEmail = 'hello@example.co.uk'; $subject = 'Contact Request from Website'; $body = '<h2>Contact Request</h2> <h4>Name</h4><p>'.$firstname. ''.$lastname.'</p> <h4>Phone Number</h4><p>'.$phonenumber.'</p> <h4>Email Address</h4><p>'.$email.'</p> <h4>Subject</h4><p>'.$selected.'</p> '; // Email Headers $headers = "MIME-VERSION: 1.0" ."\r\n"; $headers .="Content-Type:text/html;charset=UTF-8" ."\r\n"; // Additional Headers $headers .= "From: " .$firstname. " ".$lastname." <".$email.">" ."\r\n"; if(mail($toEmail, $subject, $body, $headers)) { // Message Sent $msg = 'Your message has been sent'; $msgClass = 'alert-success'; } else { // Message failed $msg = 'Your message has NOT been sent'; $msgClass = 'alert-danger'; } } } else { //Failed $msg = 'Please fill in all fields'; $msgClass = 'alert-danger'; } } ?> <div class="container clearfix content-container"> <h1 class="section-title">Contact Us</h1> <p>If you have any questions about the services we provide or would like to chat about a new website project, please get in touch using any of the options below. We would love to hear from you!</p> <!--Contact Page Row--> <div class="row"> <div class="col-lg-6 contact-details"> <div class="row"> <div class="col-lg-12"> <img src="assets/img/contact-us.jpg" class="img-responsive d-block contact-image" alt="Contact Us Image"> </div> </div> <div class="row"> <div class="col-lg-12 contact-name"> <span class="d-inline-block contact-inline-block"><i class="fas fa-user fa-2x"> </i></span> <span class="d-inline-block"><p class="contact-details">sn0wman23</p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-phone"> <span class="d-inline-block contact-inline-block"><a href="tel:+447740484798"><i class="fas fa-mobile-alt fa-2x"></i></a></span> <span class="d-inline-block"><a href="tel:+441234567890"><p class="contact-details">01234 567890</a></p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-email"> <span class="d-inline-block contact-inline-block"><a href="mailto:hello@example.co.uk"><i class="fas fa-envelope-square fa-2x"></i></a></span> <span class="d-inline-block"><a href="mailto:hello@example.co.uk"><p class="contact-details">hello@example.co.uk</a></p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-fb"> <span class="d-inline-block contact-inline-block"><a href="https://www.facebook.com/" target="_blank"><i class="fab fa-facebook-square fa-2x"></a></i></span> <span class="d-inline-block"><a href="https://www.facebook.com/example/" target="_blank"><p class="contact-details">@example</a></p></span> </div> </div> </div> <!--Contact Form--> <div class="col-lg-6 contact-form d-block"> <?php if($msg != ''): ?> <div class="alert <?php echo $msgClass; ?>"><?php echo $msg; ?></div> <?php endif;?> <form method="post" action="contact.php" role="form"> <div class=" row form-group"> <div class="col-lg-6"> <label for="firstnameid">First name:</label> <input type="text" name="firstname" class="form-control mb-3" id="firstnameid"> </div> <div class="col-lg-6"> <label for="lastnameid">Last name:</label> <input type="text" name="lastname" class="form-control mb-3" id="lastnameid"> </div> </div> <div class="row form-group"> <div class="col-lg-6"> <label for="phonenumber">Phone number:</label> <input type="tel" name="phonenumber" class="form-control mb-3" id="phonenumberid"> </div> <div class="col-lg-6"> <label for="emailid">Email address:</label> <input type="email" name="email" class="form-control mb-3" id="emailid"> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <label for="subjectid">How can I help?:</label> <select class="form-control mb-3" id="subjectid"> <option selected>Select one from this list</option> <option value="1">Value 1</option> <option value="2">Value 2</option> <option value="3">Value 3</option> </select> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <label for="messageid">Tell me a little bit mo </label> <textarea name="message" class="form-control mb-3" id="messageid" rows="6"></textarea> </div> </div> <div class="row form-group"> <div class="col-lg-12 form-check"> <input type="checkbox" name="checkbox" class="form-check-input" id="formcheckid"> <label for="formcheckid" class=form-check-label mb-3>By checking this tickbox you have confirmed that we can collect the information in this form for the purposes outlined in our <a href="privacy-policy.html">privacy policy.</a></label> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <button type="submit" name="submit" class="btn btn-primary mt-4">Send Message </button> </div> </div> </form> </div> <!--Contact Form End--> </div> <!--Contact Page Row End--> </div> <!--Container end--> <?php echo file_get_contents('footer.php'); ?>
Hello All, I am a newbie to PHP and I'm working on a marathon sign up form for my final project and could really use the help. The trouble i'm having is sending and retrieving database from the database. Below is the code i am using. Can someone please review and tell me where I went wrong.
(This is the code that is sitting at the top of my document)
<?php
}
(This is my form [submit_registration] )
<div class="contact"> |