我正在测试这个简单的登录表单。我正在使用 PHP、XAMPP,在 Chrome 中进行测试。
这是表单的代码:
<form action="login.php" method="POST">
<label>User: </label>
<input type="text" name="user" <?php if($errors){echo 'style="border:1px solid red;"';}?>>
<?php echo '<script>console.log("Value for $errors: '.$errors.'")</script>';?>
<label>Password: </label>
<input type="password" name="password" <?php if($errors){echo "style='border:1px solid red;'";}?>>
<div class="text-center">
<button type="submit" name="submit">Sign in</button>
</div>
</form>
此代码是 login.php 的一部分,在最开始,我有以下 PHP 行:
<?php
session_start();
$user = "";
$password = "";
$errors = 0;
if(isset($_POST['submit'])){
if(isset($_POST['user'])){
if(!empty($_POST['user'])){
$user = $_POST['user'];
}
}else{
$errors = 1;
}
if(!empty(isset($_POST['password']))){
$password = $_POST['password'];
}else{
$errors = 1;
}
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
}
?>
表单中的action属性调用自身(调用同一个文件-->login.php) 在 PHP 脚本中,我尝试实现如果表单已提交,则执行所有验证等。关于简单验证,我尝试将收到的 POST 值分配给变量,如果收到的内容存在且不为空.如果为空或不存在 --> $errors = 1;
问题是.. 如果两个输入有错误,我希望它们将边框颜色更改为红色。所以我做了:
<label>User: </label>
<input type="text" name="user" <?php if($errors == 1){echo 'style="border:1px solid red;"';}?>>
<?php echo '<script>console.log("Value for $errors: '.$errors.'")</script>';?>
我添加的最后几行尝试在控制台中打印 $errors 的值,它始终显示 0。
我已经尝试使用 empty($user) 进行一些重定向,当提交表单而不触及输入时,它确实显示值是空的。尽管如此,我还是不完全明白为什么 $errors 为空,其值始终为 0。
最佳答案
无需返回@Nathan-Dawson 关于您需要检查值的方式的评论/回答,这都是说的。这是一个略有不同的方法:我在之前/之后添加了警告消息,这样您就可以改善用户体验,它(希望)向您展示了如何检查值。
PHP 端
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$errors = 0; // so you don't get 'red' applied without submitting the form
if(isset($_POST['submit'])) {
if(isset($_POST['user'])){ // check for POST'd value
if(!empty($_POST['user'])){
$user = $_POST['user'];
// $errors = 0; <- $errors would remain '0' but not needed, just for the logic
} else {
$errors = 1; // form is processed but $user is POST'd empty
}
} else {
$errors = $errors; // needed if one field is set but not the other one
// so we don't set $errors back to '0'
}
// same logic applies to 'password' -> no need to comment it out again :)
if(isset($_POST['password'])){
if(!empty($_POST['password'])){
$password = $_POST['password'];
} else {
$errors = 1;
}
} else {
$errors = $errors;
}
// added this to show users if they forgot something or not
if($errors == 0) {
$warning_mess = "Form fields have been filled, thx !";
} else {
$warning_mess = "Please fill all fields before submitting.";
}
// before submitting, give users a warning about fields
} else { $warning_mess = "Form fields need to be filled"; }
?>
表单端
<input type="text" name="user"
<?php if($errors == "1"){ echo 'style="border:1px solid red;"'; } ?> />
我刚刚用 ==
添加了对 '$errors' 值的检查,以确保我们有一个 0/1 -> 如果你想稍后有所作为并设置它会很有用为每个字段设置自定义错误处理消息。
当然,您需要修剪、检查和清理来自用户的所有数据
关于php - 简单的表单验证测试 - 为空结果更改边框颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43960179/