본문 바로가기
PHP

form

by 영감은어디에 2024. 10. 10.

<?php
require 'includes/validate.php';   

$user = [
    'name'  => '',
    'age'   => '',
    'terms' => '',
];                                    

$errors = [
    'name'  => '',
    'age'   => '',
    'terms' => '',
];                     
$message = '';             

if ($_SERVER['REQUEST_METHOD'] == 'POST') {  
    $user['name']  = $_POST['name'];    
    $user['age']   = $_POST['age']; 
    $user['terms'] = (isset($_POST['terms']) and $_POST['terms'] == true) ? true : false;

    $errors['name']  = is_text($user['name'], 2, 20)   ? '' : 'Must be 2-20 characters';
    $errors['age']   = is_number($user['age'], 16, 65) ? '' : 'You must be 16-65';
    $errors['terms'] = $user['terms']                  ? '' : 'You must agree~';    
    $invalid = implode($errors);
    if ($invalid) {  
        $message = 'Please correct the following errors:'; 
    } else {     
        $message = 'Your data was valid';   
    }
}
?>
<?php include 'includes/header.php'; ?>

<?= $message ?>
<form action="validate-form.php" method="POST">
  Name: <input type="text" name="name" value="<?= htmlspecialchars($user['name']) ?>">
  <span class="error"><?= $errors['name'] ?></span><br>
  Age:  <input type="text" name="age" value="<?= htmlspecialchars($user['age']) ?>">
  <span class="error"><?= $errors['age'] ?></span><br>
  <input type="checkbox" name="terms" value="true" <?= $user['terms'] ? 'checked' : '' ?>>
  I agree ~
  <span class="error"><?= $errors['terms'] ?></span><br>
  <input type="submit" value="Save">
</form>

<?php include 'includes/footer.php'; ?>

'PHP' 카테고리의 다른 글

getting data  (0) 2024.10.11
sql  (0) 2024.10.11
date  (0) 2024.10.10
image file  (0) 2024.10.10
내장함수, number, update  (0) 2024.10.10
object  (0) 2024.10.09
function  (0) 2024.10.09
foreach  (0) 2024.10.09