0
非常にシンプルなHTMLフォームがあり、ユーザー名、パスワード、およびパスワードの確認フィールドが含まれています。フォームは入力検証のためにPHPファイルに送られます。 PHPのバリデーションファイルは、Exceptionsとtry/catchブロックを実装しています。フォームフィールドを入力せずにフォームを送信すると、最初のフィールドにのみエラーが返されます。すべてのフィールドが欠落していることを検出して、欠落しているすべてのフィールドについてエラーをスローするのはIdです。すべてのヘルプは高く評価され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
?>
:
<!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ファイルです:
は、ここに私のHTMLファイルです。ありがとう!
エラーメッセージを配列内に保存し、配列が空でない場合はすべてのエラーを表示できるform_validate()関数を呼び出す応答として配列を返すだけで例外をスローしないでください。 –