需要带有php的表单字段

时间:2011-08-26 01:56:28

标签: php forms required-field

鉴于以下代码示例,我需要将哪些内容添加到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>

1 个答案:

答案 0 :(得分:4)

<?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'