我有一个注册页面,我想对其进行验证。我有以下代码:
char
现在我该如何验证每个字段是否为空,并在嵌套的if和while的每个字段下打印不同的消息。我很困惑。
答案 0 :(得分:2)
如果您将在db中使用与表单中相同的名称,则可以使用如下形式:
$keys = ['gender', 'email', 'mobile_number']; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($key) {
if (empty($row[$key])) {
$errors[] = "$key is required"
}
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[] = "please enter $key"
}
})
}
如果您需要更多自定义消息,则可以将键映射到错误文本,例如:
$keys = ['gender' => ['equal' => 'your error message', 'empty' => 'empty msg'], 'email' => ['equal' => 'email validation error', 'empty' => 'error msg 2']]; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($errorMsg, $key) {
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[$key] = $errorMsg['equal'];
}
if (empty($row[$key])) {
$errors[$key] = $errorMsq['empty'];
}
})
}
答案 1 :(得分:0)
您可以执行以下操作。
<?php
if(isset($_POST['submit'])) {
$errors = [];
function getPost($postIndex, $errorMessage = '') {
global $errors;
if (!empty( $_POST[$postIndex] )) {
$value = $_POST[$postIndex];
return $value;;
} else {
$errors[$postIndex] = $errorMessage;
return null;
}
}
function validateString($s) {
return htmlspecialchars(trim($s));
}
getPost('First_Name', 'Firstname Cannot Be Empty');
getPost('Last_Name', 'Lastname cannot be empty');
$email = getPost('email', 'Your Error Message');
getPost('confirm_email', 'Your Error Message');
$mobile_number = getPost('mobile_number', 'Your Error Message');
getPost('password', 'Your Error Message');
getPost('confirm_password', 'Your Error Message');
getPost('gender', 'Your Error Message');
getPost('day', 'Your Error Message');
getPost('month', 'Your Error Message');
getPost('year', 'Your Error Message');
getPost('insurance', 'Your Error Message');
getPost('agree', 'Your Error Message');
$stmt = $mysqli -> prepare('SELECT email, mobile_number FROM customers WHERE email =? OR mobile_number =?');
if (
$stmt &&
$stmt -> bind_param('ss', $email, $mobile_number) &&
$stmt -> execute() &&
$stmt -> store_result() &&
$stmt -> bind_result($dbEmail, $dbMobileNumber) &&
$stmt -> fetch()
) {
if ($email == $dbEmail) {
// email equal error message
} if ($mobile_number == $row['mobile_number']) {
// mobile number equal error message
}
}
if (count($errors)) {
echo "You have an error";
}
// or get the post index in your HTML form and show the error message there
// <?php isset($errors['firstName']) ? echo $errors['firstname'] : null;
}