我有一个非常简单的HTML表单,其中包含用户名,密码和密码确认字段。表单将发送到PHP文件以进行输入验证。 PHP验证文件实现了Exceptions和try / catch块。它目前的工作方式是,如果我提交表单而不输入任何表单字段,它只会在第一个字段上返回错误。我喜欢它检测到所有字段都丢失了,并为所有缺少的字段抛出错误。
这是我的HTML文件:
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
<meta charset="UTF-8">
</head>
<body>
<h3>Register new account</h3>
<form action="HW4_action_exceptions.php" method="post">
Username:
<br/>
<input type="text" name = "user_name"/>
<br/>
Password:
<br/>
<input type="password" name ="pass_word" />
<br/>
Confirm:
<br/>
<input type="password" name = "pass_cfm" />
<br/>
<input type="submit" name="register" value="Register">
</form>
</body>
</html>
这是我的PHP文件:
<?php
if (isset($_POST['register'])) {
//put the submitted values into regular variables
$user_name = $_POST['user_name'];
$pass_word = $_POST['pass_word'];
$pass_cfm = $_POST['pass_cfm'];
//make an array of field names and data types
$field_names = array("user_name" => "string",
"pass_word" => "string",
"pass_cfm" => "string");
try {
form_validate($field_names);
} catch (Exception $e) {
echo $e->getMessage();
echo "<br>";
}
if (!isset($e) and isset($_POST['register']))
{
echo "Thanks for your entry. We'll be in touch.";
}
else
{
echo "correct form";
}
}// main if
function form_validate($fns) {
foreach ($fns as $key => $value) {
$field_value = $key;
global $$field_value;
//echo "actual field value is " . $$field_value . "<br>";
switch ($value) {
Case "string";
if ((strlen($$field_value) < 1) or ( strlen($$field_value) > 99)) {
throw new Exception("Please enter a string value between 1 and 100 characters in the <b>$key</b> field");
}
break;
default;
break;
}
}
}
// test_input
?>
感谢任何帮助。谢谢!
答案 0 :(得分:1)
不幸的是,这不适用于Exceptions。抛出异常时,会立即执行catch-block,以便跳过后面的try-block中的所有内容。
您可以尝试使用存储发生的所有错误消息的数组。
$errors = array();
switch ($value) {
Case "string";
if ((strlen($$field_value) < 1) or ( strlen($$field_value) > 99)) {
$errors[] = "Please enter a string value between 1 and 100 characters in the <b>$key</b> field");
}
break;
...
}
然后
if (count($errors) == 0 and isset($_POST['register']))
{
echo "Thanks for your entry. We'll be in touch.";
}
else
{
echo "correct form";
}
我希望这适合你。