2016-04-12 91 views
0

所以我创建了一个HTML表单,它将数据存储在数据库中,稍后我将它们存储起来,今天我想让它更先进。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 
} 
?> 

我怎样才能使它发挥作用让,你不能按提交,而你还没有完成所有的领域?

谢谢!

+0

尊敬的汤​​姆斯simpal放在

回答

0

添加name属性需要在PHP中所有必填字段

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

按钮设置

<?php 
if(isset($_POST['submit'])){ 
$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 
    } 
} 
?> 
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" /> 
1

你想要的东西客户方验证字段,然后才能提交到下一页。在jQuery中查找验证,并可能包含已添加到HTML5中的“必需”属性。

0

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

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

+0

看起来的pritty好,但我会怎么做,如果我有? –

+0

如果你添加了'required'到例如3个单选按钮上,并且'name =''',那么至少需要检查一个按钮。 – scottevans93

+0

@TomsAudrins它会提示相同。就像scottevans93所说的那样。我更新了我的答案/片段。看一看。 – rmondesilva