PHP form validation and processing same page


/ Published in: PHP
Save to your folder(s)

great to validate and process a form in the same page


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function VerifyForm(&$values, &$errors)
  4. {
  5. // Do all necessary form verification
  6.  
  7. if (strlen($values['name']) < 3)
  8. $errors['name'] = 'Name too short';
  9. elseif (strlen($values['name']) > 50)
  10. $errors['name'] = 'Name too long';
  11.  
  12. // Needs better checking ;)
  13. if (!ereg('.*@.*\..{2,4}', $values['email']))
  14. $errors['email'] = 'Email address invalid';
  15.  
  16. if (strlen($values['text']) == 0)
  17. $errors['text'] = 'Text required';
  18.  
  19. return (count($errors) == 0);
  20. }
  21.  
  22. function DisplayForm($values, $errors)
  23. {
  24. ?>
  25. <html>
  26. <head>
  27. <title>Yadda yadda</title>
  28. <style>
  29. TD.error
  30. {
  31. color: red;
  32. font-weight: bold;
  33. }
  34. </style>
  35. </head>
  36. <body>
  37.  
  38. <?php
  39. if (count($errors) > 0)
  40. echo "<p>There were some errors in your submitted form, please correct them and try again.</p>";
  41. ?>
  42.  
  43. <form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
  44. <table>
  45. <tr>
  46. <td>Name:</td>
  47. <td><input type="text" size="30" name="name" value="<?= htmlentities($values['name']) ?>"/>
  48. <td class="error"><?= $errors['name'] ?></td>
  49. </tr>
  50. <tr>
  51. <td>Email:</td>
  52. <td><input type="text" size="30" name="email" value="<?= htmlentities($values['email']) ?>"/>
  53. <td class="error"><?= $errors['email'] ?></td>
  54. </tr>
  55. <tr>
  56. <td valign="top">Text:</td>
  57. <td>
  58. <textarea name="text" cols="30" rows="6"><?= htmlentities($values['text']) ?></textarea>
  59. </td>
  60. <td class="error"><?= $errors['text'] ?></td>
  61. </tr>
  62. <tr><td colspan="2" align="center"><input type="submit" value="Submit"></tr>
  63. </table>
  64. </form>
  65.  
  66. </body>
  67. </html>
  68. <?php
  69. }
  70.  
  71. function ProcessForm($values)
  72. {
  73. mail('[email protected]', 'Form test', $values['text'], "From: \"{$values['name']}\" <{$values['email']}>");
  74.  
  75. // Replace with actual page or redirect :P
  76. echo "<html><head><title>Thank you!</title></head><body>Thank you!</body></html>";
  77. }
  78.  
  79. if ($_SERVER['REQUEST_METHOD'] == 'POST')
  80. {
  81. $formValues = $_POST;
  82. $formErrors = array();
  83.  
  84. if (!VerifyForm($formValues, $formErrors))
  85. DisplayForm($formValues, $formErrors);
  86. else
  87. ProcessForm($formValues);
  88. }
  89. else
  90. DisplayForm(null, null);
  91. ?>

URL: http://support.jodohost.com/showthread.php?t=4350

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.