对于下面的代码示例,我需要向check_input函数添加什么,以便它处理缺失/必需的表单字段。基本上,我所要做的就是在最终用户试图提交表单而不填写所有必需的字段时,在我的表单顶部显示一条错误消息,上面写着"标有*的字段是必需的"。
任何帮助都将是非常感激的,提前感谢您的时间。
// Don't post the form until the submit button is pressed.
if(isset($_POST['submit'])) {
echo(
check_input($_POST['name']) . <br> .
check_input($_POST['city']);
}
// check_input function
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data, ENT_QUOTES);
return $data;
}
的形式<form action="test.php" method="post">
<input type="text" name="name">
<input type="text" name="city">
<input type="submit" name="submit" value="submit">
</form>
<?php
// Don't post the form until the submit button is pressed.
$requiredFields = array('name', 'city'); // Add the 'name' for all required fields to this array
$errors = false;
if(isset($_POST['submit']))
{
// Clean all inputs
array_walk($_POST, 'check_input');
// Loop over requiredFields and output error if any are empty
foreach($requiredFields as $r) {
if( strlen($_POST[$r]) == 0 ) {
$errors = true;
break;
}
}
// Error/success check
if( $errors == true ) {
echo 'Fields marked with a * are required';
}else{
// no errors
// ...
}
}
// check_input function
function check_input(&$data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data, ENT_QUOTES);
return $data;
}
?>
PS:我注意到一个引号不匹配在你的表单HTML。该方法应该读取method="post"
,而不是method="post'
。