如果我有一些基本的表单验证,(只是为了简单而使用empty())并希望将这些错误消息放入数组中,我将如何实现?
$errors = array();
$response = array();
if(empty($_POST['name'])) {
$errors['name'] = "Name required";
}
if(empty($_POST['email'])) {
$errors['email'] = "Email required";
}
$response['errors'] = $errors;
if(!empty($errors)) {
$response['success'] = false;
$response['message'] = "fail";
} else {
$response['success'] = true;
$response['message'] = "<div class='alert alert-success'>Success</div>";
}
echo json_encode($response);
}
答案 0 :(得分:1)
$message = [];
if(empty($_POST['name'])) {
array_push($message , "Name required <br />");
}
if(empty($_POST['email'])) {
array_push($message , "Email required <br />");
}
if(!empty($message)) {
foreach ( $message as $str)
echo "<div class='alert alert-danger'>" . $str . "</div>";
} else {
// success
}