HTML表单提交按钮检查

时间:2016-04-12 11:02:44

标签: php

所以我创建了一个HTML表单,它将数据存储在数据库中,稍后我就把它们拿走了,今天我想让它更高级。

所以我有一个看起来像这样的表单(不是用于登录,仅举例)

<form method="post" action="process.php" autocomplete="off">

Name: <input type="text" name="name"/>
Surname: <input type="text" name="surname" />
Phone: <input type="text" name="phone" />

<input type="submit" />

在process.php中它将数据存储在数据库中,以便稍后我可以使用它们。 我想这样做,如果其中一个或多个是空的,当你按下提交按钮它会显示错误,如“必须填写所有字段”,但如果你已经完成了所有事情,它只是提交并将数据存储在数据库中。

我以为我可以用这种代码制作

<?php
$required = array('name', 'surname', 'phone');

$error = false;
foreach($required as $field) {
  if (empty($_POST[$field])) {
    $error = true;
  }
}

if ($error) {
  write and error message and don't react to submit
} else {
  if everything is done, allow to submit
}
 ?>

如何让它工作,在你没有完成所有领域时你不能按提交?

谢谢!

4 个答案:

答案 0 :(得分:1)

在您能够提交到下一页之前,您需要客户端验证字段。在jQuery中查找验证,可能包括&#34; required&#34;已添加到HTML5中的属性。

答案 1 :(得分:0)

将名称属性添加到所有必填字段所需的按钮组

select p, (select i from Item where p.product_id = i.item_id) from Product p

在php中

<input name="submit" type="submit" />

答案 2 :(得分:0)

尝试以下代码

   <?php
    if(isset($_POST['submit'])){
            $required = array('name', 'surname', 'phone');

            $error = false;
            $message='';
            foreach($required as $field) {
              if (empty($_POST[$field])) {
                $error = true;
              }
            }

            if ($error) {
                $message = 'All fields required';
                }else{
    //Submit process here

            }

    }
     ?>
    <?php echo $message; ?>
    <form method="post" action="process.php" autocomplete="off">

    Name: <input type="text" name="name"/>
    Surname: <input type="text" name="surname" />
    Phone: <input type="text" name="phone" />

    <input type="submit" name="submit" value="Submit" />

答案 3 :(得分:0)

最简单,最快捷的方式,您可以使用HTML5 required

&#13;
&#13;
<form method="post" action="process.php" autocomplete="off">

Name: <input type="text" name="name" required />
<BR>
Surname: <input type="text" name="surname" required />
<BR>
Phone: <input type="text" name="phone" required />
<BR>
Gender: Male <input type="radio" name="gender" value="1" required />
        Female <input type="radio" name="gender" value="2" required />
<BR>
<input type="submit" />
  
</form>
&#13;
&#13;
&#13;