PHP - Where Should Validation Be Performed?
Where should the validation take place? Several options include: In the Slim closure. i.e. $app->get('/', function(){/* validate before calling service */}) In the service. In the mapper. In the entity domain.I can easily create the standalone Validator class to validate scenarios such as whether a property is provided and whether it meets certain rules, however, other scenarios such as whether a record exists is closely linked to the mapper. Also, the entity does a good job confirming that the write properties are being provided. How important is it to locate validation at one place? Thanks <?php use \Psr\Http\Message\ServerRequestInterface as Request; use \Psr\Http\Message\ResponseInterface as Response; $c = new \Slim\Container(); $c['validator'] = function ($c) {}; $c['pdo'] = function ($c) {}; $c['resourceService'] = function ($c) { return new Resource\ResourceService( new Resource\ResourceMapper( $c['pdo'], $c['validator'] ), $c['validator'] ); }; $c['resourceResponder'] = function ($c) {}; $app = new \Slim\App($c); $app->get('/someResource', function (Request $request, Response $response) { return $this->resourceResponder->index($response, $this->resourceService->index($request->getQueryParams())); }); $app->get('/someResource/{id:[0-9]+}', function (Request $request, Response $response, $args) { return $this->resourceResponder->detail($response, $this->resourceService->read($args['id'])); }); $app->post('/someResource', function (Request $request, Response $response, $args) { return $this->resourceResponder->create($response, $this->resourceService->create($request->getParsedBody())); }); $app->put('/someResource/{id:[0-9]+}', function (Request $request, Response $response, $args) { return $this->resourceResponder->update($response, $this->resourceService->update($args['id'], $request->getParsedBody())); }); $app->delete('/someResource/{id:[0-9]+}', function (Request $request, Response $response, $args) { return $this->resourceResponder->delete($response, $this->resourceService->delete($args['id'])); }); $app->run(); class ResourceService { protected $mapper, $validator; public function __construct(Mapper $mapper, Validator $validator) { $this->mapper = $mapper; $this->validator = $validator; } public function index(array $params=[]):array { $index = $this->mapper->index($params); return $index; } public function read(int $id):Entity { $entity = $this->mapper->read($id); return $entity; } public function create(array $params):int { $entity=$this->mapper->create($params); $id=$this->mapper->save($entity); return $id; } public function update(int $id, array $params):int { $this->update->update($id, $params); return $id; } public function delete(int $id):null { $this->mapper->delete($id); } } class ResourceMapper { protected $pdo, $validator; public function __construct(\Pdo $pdo, Validator $validator) { $this->pdo = $pdo; $this->validator = $validator; } public function index(array $params=[]):array { //query DB and return an array of Resources } public function read(int $id):Entity { if(!$params=$this->queryDatabase($id)) { throw new \Exception("ID $id does not exist"); } return new Resource($params); } public function create(array $params):int { //Or should the service create the entity? return new ResourceEntity($params); } public function save(Entity $entity):int { //Save the data. What if a duplicate error? return $this->pdo->lastInsertId(); } public function update(int $id, array $params):null { //update database. What if id doesn't exist? } public function delete(int $id):null { //Delete from DB. What if id doesn't exist or foreign key constraint? } } class ResourceEntity { public function __construct(array $params, Validator $validator) { //As applicable } }
Similar TutorialsUsing MVC, the controller does some logic, gets data from the model, and the view presents the content.
Where should the reverse be performed?
For instance, I have an edit page which is pre-populated with values from the model, and the view changes 1000 to $1,000, 0.4 to 40%, and 2014-10-09 09:31:41 to 10/09/2014 09:31:41 AM.
Now I need to save the values, and must convert them back to their original format before doing so. Should this functionality be performed in the controller, model, or view?
Thanks
I'm having trouble with a script and I just can't figure out what's wrong with it. The script is located at http://www.qlhosting.com/ham/check.php Here's the code for it <?php if (isset($_POST['submit'])) { $domain = $_POST['domain']; $password = md5($_POST['password']); include 'db.php'; mysql_query("SELECT * FROM apps WHERE domain='$domain' AND WHERE cpassmd5='$password' LIMIT 1"); $stat = $row['status']; } else { } ?> <!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>Quotaless Web Hosting | Check Status</title> <style type="text/css"> body,td,th { font-family: Arial, Helvetica, sans-serif; font-size: 12px; } </style> </head> <body> <h1>Check Application/Account Status</h1> <?php if ($stat="PENDING") { echo "<hr />"; echo "Your application is currently listed as PENDING. Our staff have not viewed your application yet. Please be patient, and watch your email for a response. Thank you!"; } elseif ($stat="NMI") { echo "<hr />"; echo "We need more information from you in order to take action on your application. Please check your e-mail inbox for a message from our staff specifically stating what we need. If you did not get this message, please post a message on our support forum. Thank you!"; } else { } ?> <hr /> <h2>To check the status of your application or account, login using the form below.</h2> <form id="check" name="check" method="post" action="<?php echo $PHP_SELF;?>"> <p>Domain: <input type="text" name="domain" id="domain" /> <br /> Password: <input type="password" name="password" id="password" /> <br /> <input type="submit" name="button" id="button" value="Check" /> </p> </form> <hr /> <p> </p> </body> </html> The part under if ($stat="PENDING") is performed upon page load, even when the if condition relating to it is false. I can't seem to figure out what exactly is wrong here. Please help me out. I would really appreciate the help. Thanks! Anthony So Im in the weird place where my age validation is not working, any ideas: $dob = strtotime($_POST['dob']); //855993600 Feb 15th 1997 $age_req = strtotime('-13 year', $dob); //445680000 Feb 15th 1984 $time = time(); //1292007621 if ($time < $age_req){} I'm looking for a bit of help introducing some validation into my "contact us" page. I'm looking to make the user have to enter an email address into textbox And something into the Enquiry box. My 2 files are below: contact-us.shtml 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=utf-8" /> <title>Byrne Computing Services</title> <link href="styles.css" rel="stylesheet" type="text/css" /> <script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script> <link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="inc/jquery.js"></script> <script type="text/javascript" src="inc/easySlider.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#slider").easySlider(); }); </script> </head> <body> <div id="wrapper"> <!--#include file="inc_header.html" --> <!--#include file="inc_scrollingimages.html" --> <div id="boxesholder"> <!--#include file="inc_specials.html" --> <div id="main"> <div id="mainheader"> Contact Us</div> <div id="maincontent2"> <h2>Fill in the form below and we will contact you shortly.</h2> <p><img src="images/binarycode.jpg" alt="Binary Code" width="167" height="600" class="images" /><form id="form1" name="form1" method="post" action="mailer.php?mail=1"> <strong>Name: </strong><br /> <input name="name" type="text" class="formsingle" id="name" /> <br /> <br /> <strong>Email:</strong><br /> <input name="email" type="text" class="formsingle" id="emailaddress" /> <br /> <br /> <strong>Interested in:</strong><br /> <table border="0" cellspacing="0" cellpadding="0" class="table"> <tr> <td class="interestedin"><strong>Computer Repair</strong></td> <td class="interestedin"><strong>Console Repair</strong></td> <td class="interestedin"><strong>Other Services</strong></td> </tr> <tr> <td class="interestedin"> <input name="virusandmalwareremoval" type="checkbox" class="formcheckbox" id="virusandmalwareremoval" value="virusandmalwareremoval" /> <label for="virusandmalwareremoval">Virus and Malware Removal</label> </td> <td class="interestedin"> <input name="xbox360drivereplacement" type="checkbox" class="formcheckbox" id="xbox360drivereplacement" value="xbox360drivereplacement" /> <label for="ps3drivereplacement">Xbox 360 Drive Replacement</label> </td> <td class="interestedin"> <input name="databackup" type="checkbox" class="formcheckbox" id="databackup" value="databackup" /> <label for="databackup">Data Backup</label> </td> </tr> <tr> <td class="interestedin"> <input name="fullservice" type="checkbox" class="formcheckbox" id="fullservice" value="fullservice" /> <label for="fullservice">Full Service</label> </td> <td class="interestedin"> <input name="xbox360laserreplacement" type="checkbox" class="formcheckbox" id="xbox360laserreplacement" value="xbox360laserreplacement" /> <label for="ps3laserreplacement">Xbox 360 Laser Replacement</label> </td> <td class="interestedin"> <input name="websites" type="checkbox" class="formcheckbox" id="websites" value="websites" /> <label for="websites">Web Design</label> </td> </tr> <tr> <td class="interestedin"> <input name="quickfix" type="checkbox" class="formcheckbox" id="quickfix" value="quickfix" /> <label for="quickfix">Quick Fix</label> </td> <td class="interestedin"> <input name="xbox360rrodrepair" type="checkbox" class="formcheckbox" id="xbox360rrodrepair" value="xbox360rrodrepair" /> <label for="ps3ylodrepair">Xbox 360 RROD Repair</label> </td> <td class="interestedin"> <input name="datarecovery" type="checkbox" class="formcheckbox" id="datarecovery" value="datarecovery" /> <label for="datarecovery">Data Recovery</label> </td> </tr> <tr> <td class="interestedin"> <input name="upgrades" type="checkbox" class="formcheckbox" id="upgrades" value="upgrades" /> <label for="upgrades">Upgrades</label> </td> <td class="interestedin"><input name="ps3drivereplacement" type="checkbox" class="formcheckbox" id="ps3drivereplacement" value="ps3drivereplacement" /> <label for="ps3drivereplacement">PS3 Drive Replacement</label></td> <td class="interestedin"> <input name="networkinstallation" type="checkbox" class="formcheckbox" id="networkinstallation" value="networkinstallation" /> <label for="networkinstallation">Network Installation</label> </td> </tr> <tr> <td> </td> <td class="interestedin"><input name="ps3laserreplacement" type="checkbox" class="formcheckbox" id="ps3laserreplacement" value="ps3laserreplacement" /> PS3 <label for="ps3laserreplacement"> Laser Replacement</label></td> <td class="interestedin"> <input name="mobilephoneissues" type="checkbox" class="formcheckbox" id="mobilephoneissues" value="mobilephoneissues" /> <label for="mobilephoneissues">Mobile Phone Issues</label> </td> </tr> <tr> <td> </td> <td class="interestedin"><input name="ps3ylodrepair" type="checkbox" class="formcheckbox" id="ps3ylodrepair" value="ps3ylodrepair" /> <label for="ps3ylodrepair">PS3 YLOD Repair</label></td> <td class="interestedin"> <input name="emailconfiguration" type="checkbox" class="formcheckbox" id="emailconfiguration" value="emailconfiguration" /> <label for="emailconfiguration">Email Configuration</label></td> </tr> </table> <br /> <strong>Enquiry: </strong><br /> <textarea name="enquiry" class="formmulti" id="enquiry"></textarea> <br /> <br /> <input type="submit" name="button" id="button" value="Submit" /> </form> </p> <p><br /> </p> </div> </div> </div> <!--#include file="inc_offers.html" --> <!--#include file="inc_footer.html" --> </body> </html> Mailer.php Code: [Select] <?php function curPageURL() { $pageURL = 'http'; if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; } if (isset($_REQUEST['name'])) { $name = $_REQUEST['name'] ; $email = $_REQUEST['email'] ; $enquiry = $_REQUEST['enquiry'] ; if (isset($_REQUEST['virusandmalwareremoval'])){ $virusandmalwareremoval = $_REQUEST['virusandmalwareremoval'] . "\n"; } else { $virusandmalwareremoval = ""; } if (isset($_REQUEST['fullservice'])){ $fullservice = $_REQUEST['fullservice'] . "\n"; } else { $fullservice = ""; } if (isset($_REQUEST['quickfix'])){ $quickfix = $_REQUEST['quickfix'] . "\n"; } else { $quickfix = ""; } if (isset($_REQUEST['upgrades'])){ $upgrades = $_REQUEST['upgrades'] . "\n"; } else { $upgrades = ""; } if (isset($_REQUEST['xbox360drivereplacement'])){ $xbox360drivereplacement = $_REQUEST['xbox360drivereplacement'] . "\n"; } else { $xbox360drivereplacement = ""; } if (isset($_REQUEST['xbox360laserreplacement'])){ $xbox360laserreplacement = $_REQUEST['xbox360laserreplacement'] . "\n"; } else { $xbox360laserreplacement = ""; } if (isset($_REQUEST['xbox360rrodrepair'])){ $xbox360rrodrepair = $_REQUEST['xbox360rrodrepair'] . "\n"; } else { $xbox360rrodrepair = ""; } if (isset($_REQUEST['ps3drivereplacement'])){ $ps3drivereplacement = $_REQUEST['ps3drivereplacement'] . "\n"; } else { $ps3drivereplacement = ""; } if (isset($_REQUEST['ps3laserreplacement'])){ $ps3laserreplacement = $_REQUEST['ps3laserreplacement'] . "\n"; } else { $ps3laserreplacement = ""; } if (isset($_REQUEST['ps3ylodrepair'])){ $ps3ylodrepair = $_REQUEST['ps3ylodrepair'] . "\n"; } else { $ps3ylodrepair = ""; } if (isset($_REQUEST['databackup'])){ $databackup = $_REQUEST['databackup'] . "\n"; } else { $databackup = ""; } if (isset($_REQUEST['websites'])){ $websites = $_REQUEST['websites'] . "\n"; } else { $websites = ""; } if (isset($_REQUEST['datarecovery'])){ $datarecovery = $_REQUEST['datarecovery'] . "\n"; } else { $datarecovery = ""; } if (isset($_REQUEST['networkinstallation'])){ $networkinstallation = $_REQUEST['networkinstallation'] . "\n"; } else { $networkinstallation = ""; } if (isset($_REQUEST['mobilephoneissues'])){ $mobilephoneissues = $_REQUEST['mobilephoneissues'] . "\n"; } else { $mobilephoneissues = ""; } if (isset($_REQUEST['emailconfiguration'])){ $emailconfiguration = $_REQUEST['emailconfiguration'] . "\n"; } else { $emailconfiguration = ""; } if ( ereg( "[\r\n]", $name ) || ereg( "[\r\n]", $email ) ) { header( "Location: http://www.parkersmedia.com/byrne" ); } $mailcontent = "Name: ".$name; $mailcontent.= "\n\nEmail: ".$email; $mailcontent.= "\n\nInterested in: \n". $virusandmalwareremoval . $fullservice . $quickfix . $upgrades . $xbox360drivereplacement . $xbox360laserreplacement . $xbox360rrodrepair . $ps3drivereplacement . $ps3laserreplacement . $ps3ylodrepair . $databackup . $websites . $datarecovery . $networkinstallation . $mobilephoneissues . $emailconfiguration; $mailcontent.= "\n\nEnquiry: " . $enquiry; mail( "info@byrnecomputingservices.ie", "Enquiry from Byrne Computing Services", "$mailcontent", "From: $name <$email>" ); } header( "Location: http://www.parkersmedia.com/byrne/thankyou.shtml" ); ?> Any help on this would be great! i am using the following to validate a submission form. when i take this validation script out, the php script works fine, however when i use it it redirects to index.html as if their was an error.... please can somebody help, ive tried and cannot see the problem? $fname = $_POST['firstname']; $lname = $_POST['lastname']; $add1 = $_POST['add1']; $add2 = $_POST['add2']; $city = $_POST['city']; $county = $_POST['county']; $country = $_POST['country']; $postcode = $_POST['postcode']; $email1 = $_POST['email1']; $email2 = $_POST['email2']; $mobile = $_POST['mobile']; $home = $_POST['home']; $time = $_POST['time']; $answer = $_POST['answer']; $job = $_POST['job']; $ip = $_SERVER['REMOTE_ADDR']; // validation $validationOK=true; if (Trim($fname)=="") $validationOK=false; if (Trim($lname)=="") $validationOK=false; if (Trim($add1)=="") $validationOK=false; if (Trim($city)=="") $validationOK=false; if (Trim($county)=="") $validationOK=false; if (Trim($country)=="") $validationOK=false; if (Trim($postcode)=="") $validationOK=false; if (Trim($email1)=="") $validationOK=false; if (Trim($email2)!=="$email1") $validationOK=false; if (Trim($mobile)=="") $validationOK=false; if (Trim($time)=="") $validationOK=false; if (Trim($answer)!=="34") $validationOK=false; if (Trim($job)=="") $validationOK=false; if (!$validationOK) { print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">"; exit; } Hi there, I am working on getting my php form validation working. I just learned why mine wasn't working and it was because I had a header(location) in the middle of the html doc. The reason I had it there was because the code I am using is placed where I want the error to show. Here is the code I am using for this part. I only have one field being validated at the moment. Code: [Select] <? session_start(); if ($_POST['submit']) { $_SESSION['City'] = $_POST['City']; $errors = ""; if(!$_SESSION['City']){ $errors = $errors . "Please enter your city<br>"; } if ($errors != "") { echo "Please check the following errors:<br>"; echo $errors; } else { header("Location: nextpage.php"); } } ?> My question is: What way would you reorganize this (scrapy) validation to where I can redirect my user to a new page when there is no error value? The form page submits to itself with POST. Thanks for your help. I am really new to using php validation, I think I may be on to what I am looking for but not very sure. I am trying to validate my form fields just incase someone forgets (name, subject, message, and email). Here is what I have so far. I was looking at an example on how to validate a phone number. 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=utf-8" /> <title>Contact</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <?php $first_name=$_POST['name']; $email_address=$_POST['email']; $subject=$_POST['subject']; $message=$_POST['text']; if(isset($_GET['submit'])) { if(preg_match("/^\(([ $_GET['email']) != ) { echo "The email field was invalid<BR>"; } else if(isset($_GET['submit'])) { if(preg_match("/^\(([ $_GET['name']) != "") { echo "The name field was invalid<BR>"; } else if(isset($_GET['submit'])) { if(preg_match("/^\(([ $_GET['subject']) != "") { echo "The subject field was invalid<BR>"; } else { mail("myemailaddress@gmail.com","Subject: $subject", $message, "From: $first_name <$email_address>"); echo "Thank you for using our mail form.<br/>"; echo "Your email has been sent."; } ?> </body> </html> Hi, Im making a form that contains 3 textboxes.. now i want my textboxes to contain only letters.. i used is_numeric for the validation but when i put' like.. "JUSHIRO1" my code will still accept it. can someone help me make a code that will validate my textbox to only accept letters. and one more.. when the user input in the textbox with a number a popup box will appear. I have a form validation script which is written in php.. I want to add a validation (in registration form) that if the desired username contains either admin or owner keyword user will have to change his user name.. I made the following code but it does not work.. if(strpos($user_name, "admin")>=0 || strpos($user_name, "moderator")>=0 || strpos($user_name, "owner")>=0) { $error=$error."You are not allowed to take such Username<br>"; $bool=false; } In this code i am not able to enter any username.. And if i change >= to > then "admin123" username is going to be valid... I am troubled .... help me out guyzzz -pranshu.a.11@gmail.com I need to validate first name, last name, street, suburb, postcode, email, status and date of birth. I tried to do this validation but gave me heaps of error and I messed up more. Spoiler if (empty($firstname)) {$errors[] =" First Name Can not be Empty <br> ";} if (empty($lastname)) {$errors[] =" Last Name Can not be Empty <br> ";} if (empty($street)) {$errors[] =" Street Can not be Empty <br> ";} if (empty($suburb)) {$errors[] =" Suburb Can not be Empty <br> ";} if (empty($postcode)) {$errors[] =" Postcode Can not be Empty <br> ";} // elseif (!is_numeric($postcode)) {$errors[] =" Postcode must be numeric ";} elseif(!preg_match("/\^\(\[0\-9\]\{5\}\(\[\-\\s\]\?\[0\-9\]\{4\}\)\?\)\$/", $postcode)) {$errors[] =" Please enter a valid post number <br> ";} if( !preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/i", $myemail) ) {$errors[] =" You have entered and invalid email address <br> ";} if (empty($DOB)) {$errors[] =" Date only <br> ";} Chaps, as a beginner developing his first web app in PHP, I have done fairly well.
However, I am struggling when it comes to validation.
I have written different ELSEIF statements as seen below which would actually carry out the validation itself.
// First name must be filled and in correct format. if(empty($FirstName)) { $errFirstName = '<p class="errText"> Please enter a value</p>'; echo $errFirstName; }elseif(!preg_match('/^[a-z]+$/i',$FirstName)){ $errFirstName = '<p class="errText">Name may not start with a dash. Letters, spaces and dashes are accepted.</p>'; echo $errFirstName; }The problem is that I do not know how to make them "pop up" when the user makes a mistake. I have a form in addteam.php seen below: <form action="pushteam.php" method="post"> <p>Team name: <input type="text" name="TeamName" /></p> <p>Description: </p> <p><textarea name="Description" rows="4" cols="50">Add your description here.</textarea></p> <p><input type="submit"/></p> </form>And a pushplayer.php script that pushes it to a mysql database: // Get values from form $TeamName=$_POST['TeamName']; $Description=$_POST['Description']; } // Insert data into database $sql="INSERT INTO Teams(TeamName, Description)VALUES('$TeamName', '$Description')"; $result=mysql_query($sql); //If successful return to success.php else print error if($result){ header( 'Location: success.php'); } else { header( 'Location: failure.php'); }The scripts function properly. I would really appreciate if someone could guide me in the right direction here. Make the error pop up and make sure the data is not input. At the moment, if I add my ELSEIF statements, it will carry on and insert the data anyway and redirect me. Thanks Hello I have a textbox and a input button which will insert a mysql record, however i need to validate that textbox if its empty it shouldnt allow that button to insert any record but show a popup error. my script : <script Language="JavaScript"> function Blank_TextField_Validator() { // Check the value of the element named text_name // from the form named text_form if (frmContact.id.value == "") { // If null display and alert box alert("Please fill in the text field."); // Place the cursor on the field for revision frmContact.id.focus(); // return false to stop further processing return (false); } // If text_name is not null continue processing return (true); } </script>Form : <form name="frmContact" id="frmContact" method="POST" action="index.php" onsubmit="return Blank_TextField_Validator()">however its not validating or showing any error. any help? Edited by sam20e, 11 November 2014 - 10:31 AM. im looking to validate an email address before it gets sent to mysql database currently my code checks if an email address is present and if an email address already exists how do you check to see if an address contains a . and a @ symbol? Code: [Select] if($email == '') { $errmsg_arr[] = 'Email is missing'; $errflag = true; } if($email != '') { $qry = "SELECT * FROM users WHERE email='$email'"; $result = mysql_query($qry); if($result) { if(mysql_num_rows($result) > 0) { $errmsg_arr[] = 'Email address already in use'; $errflag = true; } @mysql_free_result($result); } else { die("Query failed"); } } Thanks in advance Hi, I have a mistmatched tag <messagesss></message> BUT it still displays "Validated XML!" BUT then proceeds to the else that outputs each XML error! here is the XML: Code: [Select] <?xml version="1.0" encoding="utf-8"?> <email> <messagesss> <to> <toFirstName>Tove</toFirstName> <toLastName toType="common" style="swag">Smith</toLastName> </to> <from><fromdd/> <fromFirstName>Jani</fromFirstName> <fromLastName fromType="unique">Dravison</fromLastName> </from> </message> </email> Code: [Select] <?php $dom=new DOMDocument(); $dom->load("emailSimple.xml"); $isValidated=false; $dom->formatOutput = true; $dom->saveXML(); $errors=libxml_get_errors();//Returns array where each XML file line is an elem if(!file_exists("emailSimple.xml")) print "no such file!"; else if(strlen(file_get_contents("emailSimple.xml"))==0) print "File is empty!"; else if($dom) {//IF file exists and has content if(empty($errors)) print "Validated XML!";//isValidated=true so now shred! else { //CHECK if current XML file is Well-formed foreach($errors AS $error) {//FOR EACH ERROR OF CURRENT XML FILE TO CHECK echo "Error Code: ".$error->code."<br />"; echo "Error message: ".$error->message; //Column is the end of the line where error is echo "line".$error->line.", column".$error->column."<br />"; echo "----------------------------------------------<br /><br />"; } } libxml_clear_errors(); } ?> 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) Hi, I have done email validation. At present it shows invalid email address if I kept blank but in the same time inserted the records in database. I want user to stay at the same page if anything is invalid. if(!empty($_POST['emailId'])){ if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $_POST['emailId'])){ $records['Email']=$_POST['emailId']; } else{ $emsg="Please enter valid Email address"; }} else{ $emsg="Please enter valid Email address"; } And I have used like <tr><td>Email id</td><td><input type="text" name="emailId"></td><td><?php echo ".$emsg." ;?></td></tr> Can anybody help me in this regard? First thing when i submit the form,values are not posted to the database table second thing its just displaying the error messages even if i submit the form.. third thing i dont know about the file upload i just got this code from google.. Hey guys.. I'm completely done with my contact form data validation except I cannot seem to get one part. For my email field I need to make sure that it is a valid email address and not just words. Also, I would like to make the phone number specific length. Any ideas on how to go about this? thanks guys! <?php ini_set('display_errors', '0'); //Define Variables. $FirstName = $_GET['FirstNameTextBox']; $LastName = $_GET['LastNameTextBox']; $PhoneNumber = $_GET['PhoneNumberTextBox']; $EmailAddress = $_GET['EmailAddressTextBox']; $Address = $_GET['AddressTextBox']; $City = $_GET['CityTextBox']; $State = $_GET['StateDropDownBox']; $Zip = $_GET['ZipTextBox']; $error1='*Please enter a First Name<br>'; $error2='*Please enter a Last Name<br>'; $error3='*Please enter a Phone Number<br>'; $error4='*Please choose a state<br>'; $error5='*Please enter a valid email address<br>'; $day2 = mktime(0,0,0,date("m"),date("d")+2,date("Y")); $day3 = mktime(0,0,0,date("m"),date("d")+3,date("Y")); $day7 = mktime(0,0,0,date("m"),date("d")+7,date("Y")); // Array to collect messages $messages = array(); //Display errors. if($FirstName=="") {$messages[] = $error1; } if($LastName=="") {$messages[] = $error2; } if($PhoneNumber=="") {$messages[] = $error3; } if($State=="") {$messages[] = $error4; } if($EmailAddress=="") {$messages[] = $error5; } // Don't do this part unless we have no errors if (empty($messages)) { //Display correct contact date. if($State == "NY") { $messages[] = "Hello $FirstName $LastName! Thank you for contacting me. I will get back to you within 2 days, before " .date("d M Y", $day2); } if($State == "NJ") { $messages[] = "$Hello FirstName $LastName! Thank you for contacting me. I will get back to you within 3 days, before " .date("d M Y", $day3); } if($State == "Other") { $messages[] = "$Hello FirstName $LastName! Thank you for contacting me. I will get back to you within 1 week, before " .date("d M Y", $day7); } } // END if empty($messages echo implode('<BR>', $messages); ?> <p>--<a href="Contact_Form.html" class="style2"><span class="style1">Go Back</span></a>--</p> </body> </html> 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. |