Advertisement
Guest User

Basic Php form validation

a guest
Nov 4th, 2018
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.75 KB | None | 0 0
  1. <?php
  2. function user_form_validate(array $input)
  3. {
  4.     $errors = [];
  5.     if($input['email'] == '') {
  6.         $errors['email'][] = 'Email address is required.';
  7.     } elseif(filter_var($input['email'], FILTER_VALIDATE_EMAIL) === false) {
  8.         $errors['email'][] = 'Email address must be valid.';
  9.     }
  10.  
  11.     return $errors;
  12. }
  13.  
  14. function user_form_html_render(
  15.         $action = '',
  16.         array $input,
  17.         array $errors
  18.     )
  19. {
  20.     ?>
  21.     <form method='POST' action="<?= $action ?>">
  22.         <label for="email">Email address:</label>
  23.         <input type="text" name="email" id="email" value=
  24.         "<?= html_escape($input['email']) ?>">
  25.         <?=  html_list($errors['email']) ?>
  26.         <input type="submit">
  27.     </form>
  28.     <?php
  29. }
  30.  
  31. function html_escape($string) {
  32.     return htmlspecialchars($string);
  33. };
  34.  
  35. function html_list($messages) {
  36.     return
  37.         empty($messages) || !is_array($messages)
  38.         ? ''
  39.         : '<ul><li>' .
  40.         implode('</li><li>', array_map('html_escape', $messages)) .
  41.         '</li></ul>';
  42. };
  43.  
  44. $input  = ['email' => null];
  45. $errors = $input;
  46.  
  47. if($_SERVER['REQUEST_METHOD'] == 'POST') {
  48.     $filtered = array_filter($_POST, 'is_string');
  49.     $filtered = array_map('trim', $filtered);
  50.     foreach($input as $k => $v)
  51.         if(isset($filtered[$k]))
  52.             $input[$k] = $v;
  53.     $errors   = user_form_validate($input);
  54.     $valid    = empty(array_filter($errors));
  55.  
  56.     if($valid) {
  57.         // Form values look good, do what you want with values.
  58.         echo 'Email address entered is: ' . $input['email'];
  59.     } else {
  60.         // Display form with data and errors
  61.         user_form_html_render('', $input, $errors);
  62.     }
  63. } else {
  64.     user_form_html_render('', $input, $errors);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement