我使用bootstrap ..我需要一次显示1个错误。以下代码将错误发布在不同的行中,并占用整个页面。
如果第一个字段中存在问题,则只能在继续下一个字段之前发布该错误,而不是一次发布所有字段。
function validate_registration(){
$errors = [];
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$email = clean($_POST['email']);
$user_name = clean($_POST['user_name']);
$birthdate = clean($_POST['birthdate']);
$country = clean($_POST['country']);
$password = clean($_POST['password']);
$confirm_password = clean($_POST['confirm_password']);
if (empty($email)) {
$errors[] = "Email Address Required.";
}
if (email_exists($email)) {
$errors[] = "Email Address in use.";
}
if (empty($user_name)) {
$errors[] = "Username Required.";
}
if (strlen($user_name) < $min) {
$errors[] = "Username is to short.";
}
if (user_exists($user_name)) {
$errors[] = "Username Taken.";
}
if (empty($birthdate)) {
$errors[] = "Birthdate Required.";
}
if (empty($country)) {
$errors[] = "Country Required.";
}
if (empty($password)) {
$errors[] = "Password Required.";
}
if ($password !== $confirm_password) {
$errors[] = "Your password fields do not match";
}
if (! empty($errors)) {
foreach ($errors as $error) {
echo validation_errors($error);
}
} else {
if (register_user($email, $user_name, $birthdate, $country, $password)) {
set_message('<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
Please check your email for account Information.</div>');
redirect("../account/login.php");
}
}
}
}
答案 0 :(得分:0)
<强>更新:强>
根据您的意见,如果您想一次打印一个错误,而不是需要使用ELSEIF而不是IF:
filtered.length
答案 1 :(得分:0)
您也可以通过保留现有代码来执行相同操作。
只需替换此代码: -
if (!empty($errors)) {
echo validation_errors($errors[0]);
}
您也可以通过if else if
方式获得相同的功能。将$ error声明为字符串。
$error = '';
if(empty($email)) {
$error = "Email Address Required.";
}
else if (email_exists($email)) {
$error = "Email Address in use.";
}
else if (empty($user_name)) {
$error = "Username Required.";
}
else if (strlen($user_name) < $min) {
$error = "Username is to short.";
}
else if (user_exists($user_name)) {
$error = "Username Taken.";
}
else if (empty($birthdate)) {
$error = "Birthdate Required.";
}
else if (empty($country)) {
$error = "Country Required.";
}
else if (empty($password)) {
$error = "Password Required.";
}
else if ($password !== $confirm_password) {
$error = "Your password fields do not match";
}
if (!empty($error)) {
echo validation_errors($error);
} else {
if (register_user($email, $user_name, $birthdate, $country, $password)) {
set_message('<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
Please check your email for account Information.</div>');
redirect("../account/login.php");
}
}
对于Bootstrap验证,请访问此link: -
希望它会对你有所帮助:)。
答案 2 :(得分:0)
为什么不使用jquery验证进行客户端验证
然后使用服务器端验证,但显示为全部 循环中的错误而不是内联。
因为客户端和服务器端验证很有用