php - 使用 session_start() 和 jQuery 进行表单验证不会显示任何错误,我的错误在哪里?
问题描述
这是我UsersController
在 PHP 中进行验证的地方,我已经在 index 中开始了会话,但我不确定在哪里结束它以及如何结束它:
<?php
public function createAction(){
require "Views/Users/new.php";
if (empty($_POST["email"])) {
$validation = false;
array_push($errors, "Field 'email' is required.");
}elseif (!filter_var($_POST["email"],FILTER_VALIDATE_EMAIL))
{
$validation = false;
array_push($errors, "Field'email' invalid format.");
}
if ($validation) {
$user = new Users();
$user->email = $_POST["email"];
$status = Users::insert($user);
}
if ($validation) {
$_SESSION["users-create-errors"] = $errors;
if (array_key_exists("users-create-errors", $_SESSION))
{
unset($_SESSION["users-create-errors"]);
}
}
}
}
}
解决方案
<?php
public function createAction(){
require "Views/Users/new.php";
// initialise $validation and $errors
$validation = true;
$errors = [];
if (empty($_POST["email"])) {
$validation = false;
array_push($errors, "Field 'email' is required.");
} elseif (!filter_var($_POST["email"],FILTER_VALIDATE_EMAIL)) {
$validation = false;
array_push($errors, "Field'email' invalid format.");
}
if ($validation) {
$user = new Users();
$user->email = $_POST["email"];
$status = Users::insert($user);
}
// this probably should be !$validation
if (!$validation) {
// you set $_SESSION["users-create-errors"]
// and then if its set which it of course will be
// you destroy it?????
//$_SESSION["users-create-errors"] = $errors;
//if (array_key_exists("users-create-errors", $_SESSION)) {
//unset($_SESSION["users-create-errors"]);
//}
// just set it to a new value which will overwrite anything
// that is left in there. But this shoudl be cleaned out
// when the errors have been reported to the user
$_SESSION["users-create-errors"] = $errors;
}
推荐阅读
- database - MongoDB 如何从 $lookup 远程集合中 $project(限制字段)?
- javascript - ConstantSourceNode 设置的振荡器频率错误
- jquery - 如何在列表框中选择一个值并将其与其 optgroup 标签克隆到另一个列表框
- python - 如何使小部件随 PyQt5 中的窗口缩放?
- clojure - 在 Clojure 中使用 Java 哈希图
- machine-learning - Keras 中两次损失的总和(感知和 MSE)
- android - 访问 zzbgl 并覆盖已弃用的 API 时出错
- javascript - 使用 node.js 更正了大型 RESTful API 的可扩展结构
- go - 如何使用 Golang big.Int 计算`x^3 + ax + b mod p`
- angular - 动态创建 formGroupName 不起作用 - Angular 反应式表单