Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function user_form_validate(array $input)
- {
- $errors = [];
- if($input['email'] == '') {
- $errors['email'][] = 'Email address is required.';
- } elseif(filter_var($input['email'], FILTER_VALIDATE_EMAIL) === false) {
- $errors['email'][] = 'Email address must be valid.';
- }
- return $errors;
- }
- function user_form_html_render(
- $action = '',
- array $input,
- array $errors
- )
- {
- ?>
- <form method='POST' action="<?= $action ?>">
- <label for="email">Email address:</label>
- <input type="text" name="email" id="email" value=
- "<?= html_escape($input['email']) ?>">
- <?= html_list($errors['email']) ?>
- <input type="submit">
- </form>
- <?php
- }
- function html_escape($string) {
- return htmlspecialchars($string);
- };
- function html_list($messages) {
- return
- empty($messages) || !is_array($messages)
- ? ''
- : '<ul><li>' .
- implode('</li><li>', array_map('html_escape', $messages)) .
- '</li></ul>';
- };
- $input = ['email' => null];
- $errors = $input;
- if($_SERVER['REQUEST_METHOD'] == 'POST') {
- $filtered = array_filter($_POST, 'is_string');
- $filtered = array_map('trim', $filtered);
- foreach($input as $k => $v)
- if(isset($filtered[$k]))
- $input[$k] = $v;
- $errors = user_form_validate($input);
- $valid = empty(array_filter($errors));
- if($valid) {
- // Form values look good, do what you want with values.
- echo 'Email address entered is: ' . $input['email'];
- } else {
- // Display form with data and errors
- user_form_html_render('', $input, $errors);
- }
- } else {
- user_form_html_render('', $input, $errors);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement