Posted By

brownrl on 06/19/09


Tagged

form php validation


Versions (?)

Who likes this?

8 people have marked this snippet as a favorite

teedy
etangle
jseltzer
vali29
gregorio
tapdrup
nb109
catrinho


PHP Form Validation


 / Published in: PHP
 

URL: http://www.goingson.be/2009/05/my-super-awesome-php-functions-part-v.html

This is a good way to validate form input from PHP, in essence this could be a blue print for your forms.

  1. <?php
  2.  
  3.  
  4. // Quick function to loop through regexs and compare to what is in _POST
  5. //
  6. // $regs -> associative array of regular expressions
  7. // $ferrors -> error messages to display to the users asociative array
  8.  
  9. function validatePost( $regs , $ferrors )
  10. {
  11. $errors = array();
  12. foreach( $regs as $k => $v )
  13. {
  14. if( ! preg_match( $v , $_POST[$k] ) )
  15. {
  16. $errors[$k] = $ferrors[$k];
  17. }
  18. }
  19. return $errors;
  20. }
  21.  
  22.  
  23. // has the post been submitted?
  24. if( count( $_POST ) )
  25. {
  26. // yes it has been submitted so lets validate
  27. $regs['last_name'] = "/^[[:alpha:]\ -]+$/"; // require a alpha
  28. $regs['first_name'] = "/^[[:alpha:]\ -]+$/"; // require a alpha
  29. $regs['email'] = "/^..*\@..*$/"; // VERY simple email check
  30. // Use google to find better
  31.  
  32.  
  33. // Ok here are the error message to display when it is bad
  34. $ferrors['last_name'] = "Last name required";
  35. $ferrors['first_name'] = "First name required";
  36. $ferrors['email'] = "Email name required";
  37.  
  38. $errors = validatePost( $regs , $ferrors );
  39.  
  40. // Do we have errors?
  41. if( count( $errors ) == 0 )
  42. {
  43. // WE HAVE NO ERRORS DO SOMETHING
  44. // PUT IT INTO THE DATABASE, EMAIL, BOUNCE THE USER
  45. // TO A THANK YOU PAGE, ETC...
  46. }
  47. }
  48. ?>
  49.  
  50.  
  51.  
  52. <!-- OK WE ARE IN HTML -->
  53. <!-- LETS MAKE THE FORM AND NOW YOU SEE HOW SIMPLE THIS IS I HOPE -->
  54.  
  55. <form method="POST">
  56.  
  57. <p>
  58. <label>Last Name</label>
  59. <input type="text" name="last_name" value="<?= $_POST['last_name'] ?>" />
  60. <span style="color: #FF0000;"><?= $errors['last_name'] ?></span>
  61. </p>
  62.  
  63.  
  64. <p>
  65. <label>First Name</label>
  66. <input type="text" name="first_name" value="<?= $_POST['first_name'] ?>" />
  67. <span style="color: #FF0000;"><?= $errors['first_name'] ?></span>
  68. </p>
  69.  
  70.  
  71. <p>
  72. <label>Email</label>
  73. <input type="text" name="email" value="<?= $_POST['email'] ?>" />
  74. <span style="color: #FF0000;"><?= $errors['email'] ?></span>
  75. </p>
  76.  
  77.  
  78. <p>
  79. <input type="submit" name="subby" value="GO" />
  80. </p>
  81.  
  82.  
  83. </form>

Report this snippet  

You need to login to post a comment.